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

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.

Leave a Comment