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 web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
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)