最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do I create an element after the closing body tag - Stack Overflow

programmeradmin1浏览0评论

I am checking if jQuery is included in the document. If not I want create an element after the closing body tag.

<script type="text/javascript">
if( !(typeof jQuery === 'function') ){
    var script = document.createElement('script');
    script.src = '.4.4/jquery.min.js';
    script.type = 'text/javascript';
    var head = document.getElementsByTagName("head")[0];
    head.appendChild(script);
}
</script>

If I do this with the body tag it appends it to the top. I wanna either append it to the end of the body tag or right after closing it.

Please help.

I am checking if jQuery is included in the document. If not I want create an element after the closing body tag.

<script type="text/javascript">
if( !(typeof jQuery === 'function') ){
    var script = document.createElement('script');
    script.src = 'https://ajax.googleapis./ajax/libs/jquery/1.4.4/jquery.min.js';
    script.type = 'text/javascript';
    var head = document.getElementsByTagName("head")[0];
    head.appendChild(script);
}
</script>

If I do this with the body tag it appends it to the top. I wanna either append it to the end of the body tag or right after closing it.

Please help.

Share Improve this question asked Jan 25, 2011 at 10:07 AayushAayush 3,09810 gold badges50 silver badges73 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 4

Use document.body.appendChild(). It will append the element at the end of the body tag.

By the way, jAndy is right, there is little need to add a javascript file dynamically at the end of the body.

I'm assuming you want to do this because everbody is telling that it is important to put <script> nodes at the buttom from <body>. This is correct for "normal" script tags, but in your case it's a dynamically inserted script node, so it does load asyncronously. A normal script tag is blocking while executing Javascript, that's the reason why you should put those at the end of your document.

But in your case, no problem at all.

The reason to put JavaScript at the end of the document is to postpone loading it for as long as possible. If you include your code above at the bottom of your document, you should achieve the same effect, and then it does not matter where in the source it is included.

You can't have any other tags after the body closing tag (maybe head but that should be at the top). http://www.w3/TR/html401/struct/global.html#edef-HTML

发布评论

评论列表(0)

  1. 暂无评论