Emulating document.currentScript in old browsers

Posted . Visible to the public.

When you need the DOM node of a <script> tag (e.g. to read extra attributes, or to modify the DOM near it), you can usually reference it via document.currentScript.
However, document.currentScript is unsupported in ancient browsers, like Internet Explorer 11 or wkhtmltopdf's Webkit engine.

If you are not running async scripts, you can easily polyfill it:

document.scripts[document.scripts.length - 1]

It works because document.scripts grows with each <script> tag that was evaluated.
That is also the reason why this solution will not work reliably for async code.

Demo: https://codepen.io/foobear/pen/poRLxQm Show archive.org snapshot

Arne Hartherz
Last edit
Arne Hartherz
Keywords
ie11
License
Source code in this card is licensed under the MIT License.
Posted by Arne Hartherz to makandra dev (2021-04-13 15:05)