Read more

Emulating document.currentScript in old browsers

Arne Hartherz
April 13, 2021Software engineer at makandra GmbH

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.

Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

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

Posted by Arne Hartherz to makandra dev (2021-04-13 17:05)