JS: Get Current Script Tag

By Xah Lee. Date:

This is the best way to get the current script tag

// best way to get the current script tag
const scriptTag = document.currentScript;

though, doesn't seems to be supported by Internet Explorer, even version 11.

Other ways are get by id, which is very good, but requires the id tag.

[see DOM: Get Elements by ID, Tag, Name, Class, CSS Selector]

but, lastly, you can match your JavaScript file name.

// get the script element, by matching the script name
const scriptTag = document.querySelector('script[src$="my_script_name.js"]');
// alternative, get the script element, by matching the script name
const scriptTag = Array.prototype.filter.call(
    document.getElementsByTagName("script") ,
    function (e) {return e.src.indexOf("my_script_name.js") >= 0;}
)[0];
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials

  1. HTML
  2. Visual CSS
  3. JS Basics
  4. JS in Depth
  5. JS Reference
  6. DOM
  7. SVG
  8. JS Misc