动态注入JavaScript文件-为什么大多数示例会附加到头部?
在我遇到的用javascript动态注入脚本的几乎每个示例中,它都以:
In just about every example I come across for injecting a script dynamically with javascript, it ends with:
document.getElementsByTagName("head")[0].appendChild(theNewScriptTag)
即使 yepnope.js 也会在第一个脚本之前附加新脚本页面中的脚本,例如:
Even yepnope.js attaches new scripts before the first script in the page, like:
var firstScript = doc.getElementsByTagName( "script" )[ 0 ];
firstScript.parentNode.insertBefore( theNewScriptTag, firstScript );
我的问题是:为什么不将其附加到文档正文中?
document.body.appendChild(theNewScriptTag);
在我看来,getElementsByTagName
所涉及的DOM遍历-甚至整个"insertAfter = parent.insertBefore"把戏都在浪费资源.
It just seems to me that the DOM-traversal involved with getElementsByTagName
-- or even the whole "insertAfter = parent.insertBefore" trick -- is wasting resources.
将脚本动态添加到最底层是否有害?
Is there a detriment to dynamically adding your scripts to the very bottom?
严重的是,为什么我搜索时却没有出现? document.head,附加脚本的document.body
Seriously, why didn't this show up when I searched? document.head, document.body to attach scripts
注释链接到一个完美的解释:添加脚本元素的荒谬案例.
Comment links to a perfect explanation: The ridiculous case of adding a script element.
基本上,您有几种选择:
Essentially, you have several options:
-
钩头
document.getElementsByTagName('head')[0].appendChild(js)
- 专业版-大多数页面都有头像
- 缺点-并非始终自动生成;否则遍历
- Pro - most pages have a head
- Con - not always autogenerated if not; traversal
钩到身体
document.body.appendChild(js);
- 专业版-最短,无遍历
- Con -如果未从
body
的直接子级执行,则IE7中出现操作中止"错误
- Pro - shortest, no traversal
-
Con - "operation aborted" error in IE7 if not executed from direct child of
body
连接到documentElement
hook to documentElement
var html = document.documentElement;
html.insertBefore(js, html.firstChild);
- Pro - always exists, minimal traversal
- Con - or does it? (fails if first child is a comment)
连接到第一个脚本
var first = document.getElementsByTagName('script')[0];
first.parentNode.insertBefore(js, first);
- 专业版-最有可能总是从脚本调用动态负载
- Con -如果不存在以前的脚本,则会失败;遍历
- Pro - most likely always calling your dynamic load from a script
- Con - will fail if no previous scripts exist; traversal
因此,结论是-您可以以任何方式做到这一点,但您必须考虑自己的听众.如果可以控制加载程序的执行位置,则可以使用document.body
.如果加载程序是其他人使用的库的一部分,则您必须根据使用的方法给出具体说明,并为滥用规范的人员做好准备.
So, the conclusion is -- you can do it any way, but you have to think of your audience. If you have control of where your loader is being executed, you can use document.body
. If your loader is part of a library that other people use, you'll have to give specific instructions depending on what method you used, and be prepared for people abusing your specs.