Is it the last `script` element the currently running script?

前端 未结 3 409
感动是毒
感动是毒 2020-12-02 00:19

Is it safe to assume that the last script element* in the document when the script runs** is the currently running script?

For example, I want to create

相关标签:
3条回答
  • 2020-12-02 00:50

    It's not an absolute guarantee no. Check out this JSFiddle: http://jsfiddle.net/jAsek/

    <!DOCTYPE html>
    <title>Test case</title>
    <div>
        <p>At the start</p>
        <script id="first">
            var scr1 = document.createElement("script");
            scr1.setAttribute("id", "early");
            document.body.appendChild(scr1);
        </script>
        <p>After the first script</p>
        <script id="second">
            function getCurrentScriptElement() {
                var scripts = document.getElementsByTagName('script');
                return scripts[scripts.length - 1];
            }
    
            alert(getCurrentScriptElement().id);
        </script>
        <p>At the end</p>
    </div>
    

    Here the alert reports the id of the injected script "early", not the id of currently running script "second".

    There's no practical difference between internal and external scripts.

    0 讨论(0)
  • 2020-12-02 01:00

    I don’t think it’s a safe assumption at all, as browsers execute javascript code quite differently depending on a number of things (like if you have other script elements in the head, if they are external etc.).

    You should just require people to use a dummy element with a custom id or class. That way you will also make it possible to do whatever you do multiple times a page without having to run the script multiple times.

    This is also what is done when using widgets, for example Google’s +1 button.

    An alternative would be to use document.write to write additional content while the script is executed. This will not replace the script tag however, but simply add something after it.

    0 讨论(0)
  • 2020-12-02 01:01

    You probably want to use document.currentScript that is currently supported by 90% of browsers and fallback to document.scripts[document.scripts.length-1] if you're targetting IE

    function writeHere(element)
    {
     var sc = document.currentScript || document.scripts[document.scripts.length-1] ;  
     sc.parentNode.insertBefore(element, sc);
     // or in jquery $(sc).before($(element));
    }
    

    note: I didn't test document.scripts[document.scripts.length-1] thoroughly but it should work in most cases (but not in Alohci exemple).
    And this is a fix for IE so who cares :)

    0 讨论(0)
提交回复
热议问题