DEV Community

Gouranga Das Samrat
Gouranga Das Samrat

Posted on

I Missed document.currentScript for Years: Here’s Why You Shouldn’t

I Missed document.currentScript for Years: Here’s Why You Shouldn’t

I found an interesting DOM API document.currentScript while going through a newsletter issue last week. I thought it was just another browser API I’d never use. Then I found it’s just quietly powerful, ready to solve those “where did this script even come from?” moments.

Let’s have a deep dive into it.

What’s it do?

This API returns the <script> element currently executing. Think of it as a mirror for your script to check itself out mid-execution. It’s a lifesaver for tracking script origins or tweaking behavior on the fly.

<script>
  console.log("tag name:", document.currentScript.tagName);
  console.log(
    "script element?",
    document.currentScript instanceof HTMLScriptElement
  );
  // Log the src of the current script
  console.log("source:", document.currentScript.src);
  // Add a custom attribute to the script tag
  document.currentScript.setAttribute("data-loaded", "true");

  // tag name: SCRIPT
  // script element? true
</script>
Enter fullscreen mode Exit fullscreen mode

This logs the script’s source URL or sets a custom attribute. The coolest part is that it is supported in all modern browsers.

Let’s have a look at another example:

<script data-external-key="123urmom" defer>
  console.log("external key:", document.currentScript.dataset.externalKey);
  if (document.currentScript.defer) {
    console.log("script is deferred!");
  }
</script>
Enter fullscreen mode Exit fullscreen mode
// external key: 123urmom
// script is deferred!
Enter fullscreen mode Exit fullscreen mode

Watch Out for Modules and Async

An important part to remember here is that the document.currentScript is not available for a script tag whose type is module. It is set to null for this case.

<script type="module">
  console.log(document.currentScript);
  console.log(document.doesNotExist);
  // null
  // undefined
</script>
Enter fullscreen mode Exit fullscreen mode

The similar behavior can be noticed when you try to access document.currentScript in async code.

<script>
  console.log(document.currentScript);
  // <script> tag
  setTimeout(() => {
    console.log(document.currentScript);
    // null
  }, 1000);
</script>
Enter fullscreen mode Exit fullscreen mode

A Challenge More Common Than You Think

Let’s take an example of CMS platforms. CMS platforms often lock down what you can tweak. Editors might adjust bits of markup, but messing with <script> tag contents is usually off-limits.

Sometimes the scripts loaded by the CMS platforms use external libraries which need custom settings such as configuration values.

<!-- Shared library, but still requires configuration! -->
<script src="path/to/shared/signup-form.js"></script>
Enter fullscreen mode Exit fullscreen mode

A common solution for such cases is to pass in the configuration values using the data attributes.

Data attributes cleanly pass specific values from server to client. The only minor hassle is querying the element to grab its attributes.

Since we are talking about the <script> tag we can simply use document.currentScript . Let’s look at an example:

<script
  data-stripe-pricing-table="{{pricingTableId}}"
  data-stripe-publishable-key="{{publishableKey}}"
>
  const scriptData = document.currentScript.dataset;
  document.querySelectorAll("[data-pricing-table]").forEach((table) => {
    table.innerHTML = `
     <stripe-pricing-table
       pricing-table-id="${scriptData.stripePricingTable}"
       publishable-key="${scriptData.stripePublishableKey}"
       client-reference-id="picperf"
     ></stripe-pricing-table>
   `;
  });
</script>
Enter fullscreen mode Exit fullscreen mode

This feels clean. No proprietary hacks, no polluting the global scope.

Other Applications

Let’s explore some other applications of this API.

Setting Up Your Library Right

Suppose you are building a JavaScript library that needs to load asynchronously. You can make sure if it’s loaded correctly with document.currentScript. It’s a straightforward way to give devs clear feedback.

<script defer src="./script.js"></script>
Enter fullscreen mode Exit fullscreen mode

// script.js
if (!document.currentScript.async) {
throw new Error("This script must load asynchronously.");
}
// Rest of the library code...

You can also enforce where the <script> tag lives on the page. Suppose you need it to be just after the opening <body> tag.

const isFirstBodyChild =
document.body.firstElementChild === document.currentScript;
if (!isFirstBodyChild) {
throw new Error(
"This MUST be loaded immediately after the opening <body> tag."
);
}

It’s a clean way to guide developers, pairing perfectly with good documentation.

Debugging Script Origins

Suppose you need to trace a script’s source in a complex app. It can be done easily with this API:

// Log script metadata for debugging
console.log(Script: ${document.currentScript.src}, ID: ${document.currentScript.id}\);

Conditional Script Execution

Want scripts to behave differently based on their attributes? Use document.currentScript to check and act.

<script data-env="production">
  // Run logic based on script attributes
  if (document.currentScript.dataset.env === "production") {
    console.log("Production mode activated");
  }
</script>
Enter fullscreen mode Exit fullscreen mode

Final Takeaway

Today we looked at another cool JavaScript DOM API which allows to gain more control on scripts loaded on a webpage.

Try it in your projects and share your thoughts in the comment below.

Thank you. Let’s meet again with another cool JavaScript guide.

Top comments (0)