Javascript document.head, document.body 附加脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7557868/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
document.head, document.body to attach scripts
提问by graphicdivine
I have often used, and seen recommended, dom-access structures like this for adding content to pages dynamically:
我经常使用并看到推荐的像这样的 dom-access 结构来动态地向页面添加内容:
loader = document.createElement('script');
loader.src = "myurl.js";
document.getElementsByTagName('head')[0].appendChild(loader);
Now, by chance, I find that this works in Google chrome:
现在,偶然地,我发现这在谷歌浏览器中有效:
document.head.appendChild(loader);
A little more investigation, and I find that this works, apparently cross-browser:
多一点调查,我发现这很有效,显然是跨浏览器的:
document.body.appendChild(loader);
So my primary question is: are there any reasons why I shouldn't attach elements to the BODY like this?
所以我的主要问题是:有什么原因我不应该像这样将元素附加到 BODY 上?
Also, do you think document.head
will become more widely supported?
另外,您认为document.head
会得到更广泛的支持吗?
采纳答案by Daniel Brockman
I can't see any reason why it would matter in practice whether you insert your <script>
elements into the <head>
or the <body>
element. In theory, I guess it's nice to have the runtime DOM resemble the would-be static one.
我看不出有什么理由在实践中将<script>
元素插入到<head>
或<body>
元素中。从理论上讲,我想让运行时 DOM 类似于可能的静态 DOM 会很好。
As for document.head
, it's part of HTML5 and apparently already implemented in the latest builds of all major browsers (see http://www.whatwg.org/specs/web-apps/current-work/multipage/dom.html#dom-document-head).
至于document.head
,它是 HTML5 的一部分,显然已经在所有主要浏览器的最新版本中实现(参见http://www.whatwg.org/specs/web-apps/current-work/multipage/dom.html#dom-document -头)。
回答by Niko
document.body
is part of the DOM specification, I don't see any point why not to use it. But be aware of this:
document.body
是 DOM 规范的一部分,我看不出为什么不使用它。但请注意这一点:
In documents with contents, returns the element, and in frameset documents, this returns the outermost element.
在有内容的文档中,返回元素,在框架集文档中,返回最外面的元素。
(from https://developer.mozilla.org/en/DOM/document.body)
(来自https://developer.mozilla.org/en/DOM/document.body)
document.head
currently isn't defined in any DOM specification(apparently I was wrong on that, see Daniel's answer), so you should generally avoid using it.
document.head
目前没有在任何 DOM 规范中定义(显然我错了,请参阅 Daniel 的回答),因此您通常应该避免使用它。
回答by Keithasaurus Rex
I tried implementing this code and ran into a bit of trouble, so wanted to share my experience.
我尝试实现此代码并遇到了一些麻烦,所以想分享我的经验。
First I tried this:
首先我试过这个:
<script>
loader = document.createElement('script');
loader.src = "script.js";
document.getElementsByTagName('head')[0].appendChild(loader);
</script>
And in the script.js file I had code such as the following:
在 script.js 文件中,我有如下代码:
// This javascript tries to include a special css doc in the html header if windowsize is smaller than my normal conditions.
winWidth = document.etElementById() ? document.body.clientWidth : window.innerWidth;
if(winWidth <= 1280) { document.write('<link rel="stylesheet" type="text/css" href="style/screen_less_1280x.css">'); }
The problem is, when I did all of this, the code wouldn't work. Whereas it didwork once I replaced the script loader with simply this:
问题是,当我完成所有这些操作时,代码将无法工作。虽然它没有工作,一旦我替换只是这个脚本加载器:
<script src="script.js"></script>
That works for me, so problem solved for now, but I would like to understand the difference between those two approaches. Why did one work and not the other?
这对我有用,所以现在问题解决了,但我想了解这两种方法之间的区别。为什么一个有效,另一个无效?
What's more is that in script.js I also have code such as:
更重要的是,在 script.js 中,我还有如下代码:
function OpenVideo(VideoSrcURL) {
window.location.href="#OpenModal";
document.getElementsByTagName('video')[0].src=VideoSrcURL;
document.getElementsByTagName('video')[0].play();}
And that code doeswork fine regardless of which way I source the script in my html file.
无论我以哪种方式在 html 文件中获取脚本,该代码都可以正常工作。
So my window resizing script doesn't work, but the video stuff does. Therefore I'm wondering if the difference in behavior has to do with "document" object...? Maybe "document" is referencing the script.js file instead of the html file.
所以我的窗口大小调整脚本不起作用,但视频内容起作用。因此,我想知道行为的差异是否与“文档”对象有关......?也许“文档”引用的是 script.js 文件而不是 html 文件。
I don't know. Thought I should share this issue in case it applies to anyone else.
我不知道。我想我应该分享这个问题,以防它适用于其他任何人。
Cheers.
干杯。
回答by Emanuele Del Grande
The answers given as far as now focus two different aspects and are both very useful.
目前给出的答案集中在两个不同的方面,并且都非常有用。
If portability is a requirement for you, in documents not under your ownership where you can't control the DOM coherence, it may be useful to check for the existence of the element you have to append the script to; this way, it will works also when the HEAD section has not been explicitly created:
如果您需要可移植性,在您无法控制 DOM 一致性的不属于您所有的文档中,检查您必须将脚本附加到的元素是否存在可能会很有用;这样,当 HEAD 部分尚未显式创建时,它也将起作用:
var script = document.createElement('script');
var parent = document.getElementsByTagName('head').item(0) || document.documentElement;
parent.appendChild(script);
Apart of CORS policy and other easily detectable logic errors, I don't see cases in which this DOM manipulation task should fail, so checking for document.body
as a fallback is not necessary by my point of view.
除了 CORS 策略和其他易于检测的逻辑错误之外,我没有看到此 DOM 操作任务应该失败的情况,因此document.body
从我的观点来看,没有必要检查作为后备。
As other users outlined too, document.head
was not widely supported yet, at the time the question was posted, as it is a HTML5 spec, while document.body
is, that's why you saw the latter working on all the browsers.
正如其他用户所概述的document.head
那样,在发布问题时还没有得到广泛支持,因为它是 HTML5 规范,而document.body
这就是为什么你看到后者在所有浏览器上工作的原因。
So you could get the HEAD with:
所以你可以通过以下方式获得 HEAD:
document.head || document.getElementsByTagName('head').item(0)
but I don't see it very useful, as the latter won't ever be wrong and is a readable and standard DOM query, unless you find out that document.head
is faster from a performance perspective.
但我认为它不是很有用,因为后者永远不会出错,并且是可读且标准的 DOM 查询,除非您发现document.head
从性能角度来看它更快。
Another possible advantage I can see about this form is a code transition from older JavaScript to a more modern HTML5 compliant code, brief and more readable.
我可以看到关于这种形式的另一个可能的优势是代码从旧的 JavaScript 转换为更现代的 HTML5 兼容代码,简短且更具可读性。
If compatibility is a must, you could use tricks adopted by libraries for which portability is mandatory (e.g. solutions from Google, Yandex and others):
如果必须兼容,您可以使用强制可移植性的库采用的技巧(例如来自 Google、Yandex 和其他公司的解决方案):
var parent = document.getElementsByTagName('head')[0] || document.documentElement.firstChild;
parent.appendChild(script);
This way, in the improbable case the HEAD element does not exist while the BODY (or another element) does, you are sure to append the script to it.
这样,在不太可能的情况下 HEAD 元素不存在而 BODY(或其他元素)存在时,您一定要向其附加脚本。
I also add a useful bit: the HTTP request of the script source is sent from the browser when the src
attribute is set andit is appended to the DOM. No matter in which order these two conditions are met, the last of these two events causes the HTTP request to be dispatched.
我还添加了一个有用的位:当src
属性被设置并将它附加到 DOM时,脚本源的 HTTP 请求是从浏览器发送的。无论以何种顺序满足这两个条件,这两个事件中的最后一个都会导致 HTTP 请求被分派。