简体   繁体   中英

Insert elements at <script> tag position

When sites give you some JavaScript that you paste into a web page to have content inserted at that position, how does the script determine its current position in the DOM? Without using document.write?

Thanks,

Nick

At script inclusion time, it's certain that the last <script> in the page will be the current one; the rest of the page hasn't been parsed yet. 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 holds true as long as the script tag doesn't use defer , or HTML5's async .

I was looking out for the answer myself, my situation was "Create a dynamic src and add it to script element at one fixed place".

<script>Other code</script>
//Add my dynamically calculated script right here

I had used something like this

<script>document.write('<script src="myJs.js?v=' + Math.floor(Math.random() * 100) + '"\><\/script>');</script>

It worked, but lighthouse audit marked it a bad practice. To improve my performance score, I had to remove the document.write, which was used at multiple places. I wrote below function and called it wherever I wanted to add such scripts:

<script type="text/javascript">
    function insertScriptHere(src){
        var script = document.createElement('script');
        script.setAttribute("src", src + Math.floor(Math.random() * 100));
        document.currentScript.insertAdjacentElement('afterEnd', script);
    }
</script>
....
<script>insertScriptHere("myJs.js?v=");</script>

Now this is working and the flag "avoid use of document.write()" is no longer there in audit report.

I don't see why such scripts would care about their location in the DOM, but I guess it's possible to determine. Maybe use something like document.scripts to start your search.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM