Emulating document.currentScript in old browsers

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 About 3 years ago