document.head,document.body附加脚本 [英] document.head, document.body to attach scripts

查看:99
本文介绍了document.head,document.body附加脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常使用,并且看到推荐的这样的dom访问结构,用于动态地向页面添加内容:

  loader = document.createElement('script'); 
loader.src =myurl.js;
document.getElementsByTagName('head')[0] .appendChild(loader);

现在,偶然的是,我发现它适用于Google Chrome:

  document.head.appendChild(loader); 

更多的调查,我发现这个工作,显然是跨浏览器:

  document.body.appendChild(loader); 

所以我的主要问题是:是否有任何理由为什么我不应该添加元素到BODY,这个?



另外,你认为 document.head 将会得到更广泛的支持吗?

解决方案

在实践中我看不出任何理由重要,无论您是否插入脚本> 元素到< head> < body> 元素。理论上来说,我认为运行时DOM类似于静态的,很高兴。



对于 document.head ,它是HTML5的一部分,显然已经在所有主流浏览器的最新版本中实现(请参阅 http://www.whatwg.org/specs/web-apps/current-work/multipage/dom.html#dom-document-head )。


I have often used, and seen recommended, dom-access structures like this for adding content to pages dynamically:

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?

Also, do you think document.head will become more widely supported?

解决方案

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.

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,document.body附加脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆