`document.currentScript` is more useful than I thought.

Chris Coyier Chris Coyier on

Huh. Today I learned (from Alex MacArthur): you can access the current <script> element from a script (if it’s not type="module") with document.currentScript. Meaning you can put configuration data as attributes on it and pluck them off and use them. Like:

<h1 id="setMePlease"></h1>

<script data-some-value="foo">
  const scriptData = document.currentScript.dataset;
  setMePlease.textContent = scriptData.someValue;
</script>Code language: HTML, XML (xml)

It's time to take your JavaScript to the next level

Frontend Masters logo

Frontend Masters is the best place on the web to really learn JavaScript. We have a complete learning path from the biggest and best teachers in JavaScript to help you make the most out of the web's biggest language.

Leave a Reply

Your email address will not be published. Required fields are marked *

$966,000

Frontend Masters donates to open source projects through thanks.dev and Open Collective, as well as donates to non-profits like The Last Mile, Annie Canons, and Vets Who Code.