Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
341 views
Welcome To Ask or Share your Answers For Others

1 Answer

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...