异步.js文件加载语法 [英] asynchronous .js file loading syntax
问题描述
我注意到,有似乎是加载JS文件一对夫妇略有不同的语法异步,我想知道是否有任何两者之间的区别,或者如果他们都pretty非常重要的作用是相同的。我猜他们的工作是相同的,只是希望确保一种方法并不比其他更好的出于某种原因。 :)
方法一
(函数(){
变种D =文件,
H = d.getElementsByTagName(头)[0]
S = d.createElement('脚本');
s.type =文/ JavaScript的';
s.src ='/ JS / myfile.js';
h.appendChild(多个);
})(); / *注后括号和大括号* /
结果
方法二(在Facebook的code看到这个)
(函数(){
变种D =文件,
H = d.getElementsByTagName(头)[0]
S = d.createElement('脚本');
s.type =文/ JavaScript的';
s.async = TRUE;
s.src ='/ JS / myfile.js';
h.appendChild(多个);
}()); / *注后括号和大括号* /
这是我看到的唯一区别是 s.async = TRUE;
在Facebook的方法
的
异步
和延迟
属性是表明脚本应该如何执行布尔属性。
有可以使用这些属性来选择三种可能的模式。 如果是present,那么脚本将被异步,只要它是可用执行
异步
属性。如果在异步
属性不是present但defer属性为present,然后在页面完成解析执行脚本。如果没有属性是present,那么脚本被取出,并立即执行,用户代理继续解析页面之前。
块引用>来源和进一步阅读:<一href=\"http://www.whatwg.org/specs/web-apps/current-work/multipage/scripting-1.html#attr-script-async\">Whatwg.org HTML 5:脚本元素
至于优点,你可能要检查什么谷歌有这个去年12月说:
I noticed that there seems to be a couple of slightly different syntaxes for loading js files asynchronously, and I was wondering if there's any difference between the two, or if they both pretty much function the same. I'm guessing they work the same, but just wanted to make sure one method isn't better than the other for some reason. :)
Method One
(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 */
Method Two (Saw this in Facebook's code)(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 */
解决方案The only difference that I notice is the
s.async=true;
in the Facebook method.The
async
anddefer
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 theasync
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.Source and Further reading: Whatwg.org HTML 5: The script element
As for the advantages, you may want to check what Google had to say on this last December:
这篇关于异步.js文件加载语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!