Insert elements at tag position <script>

When sites give you some kind of JavaScript that you embed on a web page to add content to this position, how does the script determine its current position in the DOM? Without using document.write?

Thank,

Nick

+5
source share
2 answers

At the moment the script is enabled, he is sure that the last one <script>on the page will be current; the rest of the page has not yet been parsed. So:

<script type="text/javascript">
    var scripts= document.getElementsByTagName('script');
    var this_script= scripts[scripts.length-1];

    // Something that happens later...
    //
    setTimeout(function() {
        var div= document.createElement('div');
        div.appendChild(document.createTextNode('Hello!'));
        this_script.parentNode.insertBefore(div, this_script);
    }, 5000);
</script>

This is done if the script tag is not using deferor HTML5 async.

+5
source

, DOM, , . , document.scripts, .

0

All Articles