gpt4 book ai didi

javascript - 异步 .js 文件加载语法

转载 作者:可可西里 更新时间:2023-11-01 01:24:38 27 4
gpt4 key购买 nike

我注意到异步加载 js 文件的语法似乎略有不同,我想知道这两者之间是否有任何区别,或者它们的功能是否几乎相同。我猜他们的工作原理是一样的,但只是想确保一种方法不会因为某种原因比另一种更好。 :)

方法一

(function() {
var d=document,
h=d.getElementsByTagName('head')[0],
s=d.createElement('script');
s.type='text/javascript';
s.src='/js/myfile.js';
h.appendChild(s);
})(); /* note ending parenthesis and curly brace */


方法二(在Facebook的代码中看到这个)

(function() {
var d=document,
h=d.getElementsByTagName('head')[0],
s=d.createElement('script');
s.type='text/javascript';
s.async=true;
s.src='/js/myfile.js';
h.appendChild(s);
}()); /* note ending parenthesis and curly brace */

最佳答案

我注意到的唯一区别是 Facebook 方法中的 s.async=true;

The async and defer attributes are boolean attributes that indicate how the script should be executed.

There are three possible modes that can be selected using these attributes. If the async attribute is present, then the script will be executed asynchronously, as soon as it is available. If the async attribute is not present but the defer attribute is present, then the script is executed when the page has finished parsing. If neither attribute is present, then the script is fetched and executed immediately, before the user agent continues parsing the page.

来源和进一步阅读:Whatwg.org HTML 5: The script element

至于优势,您可能想查看 Google 在去年 12 月的评论:

关于javascript - 异步 .js 文件加载语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2774373/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com