How do I create an element after the closing body tag

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.com/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.

Answers:

Answer

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.

Answer

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.

Answer

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.

Answer

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.