Referencing a Script’s Own Tag

By  on  

Information about document.currentScript has been added to this post. document.currentScript should be considered the better option.

There are times when the contents of an external script may want to reference its own SCRIPT tag.  There are times that developers may want to detect attributes of the script tag which act as options for the script; this is a practice that's been done by the Dojo Toolkit for years.  Lea Verou's Prism syntax highlighter also uses this practice:

<!-- Traditional Dojo config -->
<script src="//ajax.googleapis.com/ajax/libs/dojo/1.8.3/dojo/dojo.js"
               data-dojo-config="async: true"></script>

<!-- Sample Prism config -->
<script src="prism.js" data-default-language="markup" data-manual></script>

So how are these projects getting the correct SCRIPT tag with which to look for attributes?  Assuming a top-down (not async) load of scripts, the following will get a script its own tag:

/* From in side the script.... */

// Reliably grab my script tag
var script = document.getElementsByTagName("script");
script = script[script.length - 1];

// Check for an attribute/config
if(script.hasAttribute('data-something')) {
	// Do something!
}

Collect the SCRIPT elements up to that point and reference the last one -- that's all you need to do.  Of course we're living in a mostly async world right now, so to accommodate for those cases, you may need to stick an ID on the SCRIPT element, take a chance matching the SCRIPT by path (a really bad idea), or use a different type of configuration system.

document.currentScript

A document.currentScript property also exists, and this standard property provides the ultimate reliable method of detecting the currently executing script:

var script = document.currentScript;

Pairing this method with the older solution, the best complete code solution could be this:

var script = document.currentScript || (function() {
    var scripts = document.getElementsByTagName("script");
    return scripts[scripts.length - 1];
})();

Recent Features

  • By
    Write Better JavaScript with Promises

    You've probably heard the talk around the water cooler about how promises are the future. All of the cool kids are using them, but you don't see what makes them so special. Can't you just use a callback? What's the big deal? In this article, we'll...

  • By
    I&#8217;m an Impostor

    This is the hardest thing I've ever had to write, much less admit to myself.  I've written resignation letters from jobs I've loved, I've ended relationships, I've failed at a host of tasks, and let myself down in my life.  All of those feelings were very...

Incredible Demos

  • By
    Spoiler Prevention with CSS Filters

    No one likes a spoiler.  Whether it be an image from an upcoming film or the result of a football match you DVR'd, sometimes you just don't want to know.  As a possible provider of spoiler content, some sites may choose to warn users ahead...

  • By
    TextboxList for MooTools and jQuery by Guillermo Rauch

    I'll be honest with you: I still haven't figured out if I like my MooTools teammate Guillermo Rauch. He's got a lot stacked up against him. He's from Argentina so I get IM'ed about 10 times a day about how great Lionel...

Discussion

  1. Very useful, but you should warn about it won’t work reliably if you load the script asynchronously (either via async attribute or from another script).

  2. Darius Kruythoff

    Basically, there’s no generic way to be 100% sure it’s the right one.

  3. Aaditya Kumar

    doing this since ages in Ad serving scripts…

  4. As an option you can use live collection called `document.scripts` instead of `document.getElementsByTagName(“script”)`

  5. James

    Another little trick that I sometimes pair with this is that once you have a handle on the script element, you can get the text within the script tag, which can allow for some more interesting configuration capabilities. I only use this when using attributes becomes overly clunky.

    In the markup:

    // configuration goes here

    In the script.js

    var script = document.getElementsByTagName(“script”);
    script = script[script.length – 1];

    configure(script.text); // script.text is the text inside the script tag in the DOM

    At this point, you can parse the script.text based on some DSL that you get to define.
    If you’re feeling particularly evil, you can eval the script.text in order to provide an injectable programmatic configuration. I still haven’t decided if I love that approach or not, personally.

  6. What about `document.currentScript`? https://developer.mozilla.org/en-US/docs/DOM/document.currentScript

    That’s been in Firefox awhile AFAIK and it’s now in the HTML5 standard: http://www.whatwg.org/specs/web-apps/current-work/multipage/dom.html#dom-tree-accessors

  7. Thanks, I can now reference label Make own script. I appreciate

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!