drz*_*aus 5 javascript optimization dom micro-optimization
在几乎所有我通过javascript动态注入脚本的例子中,它以:
document.getElementsByTagName("head")[0].appendChild(theNewScriptTag)
Run Code Online (Sandbox Code Playgroud)
甚至yepnope.js在页面中的第一个脚本之前附加新脚本,例如:
var firstScript = doc.getElementsByTagName( "script" )[ 0 ];
firstScript.parentNode.insertBefore( theNewScriptTag, firstScript );
Run Code Online (Sandbox Code Playgroud)
我的问题是:为什么不将它附加到文件正文?
document.body.appendChild(theNewScriptTag);
Run Code Online (Sandbox Code Playgroud)
在我看来,DOM遍历涉及getElementsByTagName
- 甚至整个"insertAfter = parent.insertBefore"技巧 - 浪费资源.
将脚本动态添加到最底层是否有害?
drz*_*aus 17
说真的,为什么我搜索时没出现? document.head,document.body附加脚本
评论链接到一个完美的解释:添加脚本元素的荒谬案例.
基本上,您有几种选择:
document.getElementsByTagName('head')[0].appendChild(js)
Run Code Online (Sandbox Code Playgroud)
document.body.appendChild(js);
Run Code Online (Sandbox Code Playgroud)
body
documentElement
var html = document.documentElement;
html.insertBefore(js, html.firstChild);
Run Code Online (Sandbox Code Playgroud)
var first = document.getElementsByTagName('script')[0];
first.parentNode.insertBefore(js, first);
Run Code Online (Sandbox Code Playgroud)
所以,结论是 - 你可以做任何事情,但你必须考虑你的观众.如果您可以控制加载程序的执行位置,则可以使用document.body
.如果您的加载程序是其他人使用的库的一部分,则必须根据您使用的方法提供具体说明,并为滥用您的规范的人做好准备.
归档时间: |
|
查看次数: |
5966 次 |
最近记录: |