Insert elements at <script> tag position

╄→尐↘猪︶ㄣ 提交于 2021-02-07 13:52:34

问题


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


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/2789604/insert-elements-at-script-tag-position

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!