How to determine which JavaScript file is running

In programming, context is important. Part of that context is the currently executing script file.

For example, I might need to know which directory the current JavaScript file is running in so I can refer to other resources using a relative path. Relative paths are more convenient to work with than typing out absolute paths for everything. Also, if I were using absolute paths and I moved a file or directory in my code project, I would have to update all of the absolute paths inside. So there are valid reasons for wanting to know which script file we are currently in.

Node.js makes it extremely easy to determine the current file or directory with __filename and __dirname, respectively.

Fortunately, it's not too difficult to find the same information in the browser using document.currentScript. This property returns the <script> element that is currently being executed.

console.log(document.currentScript.src)

Caveats

There are a few caveats to using document.currentScript. First, the property only references its containing <script> element if the code is executing synchronously. That means we can't use it in callbacks and event handlers. Fortunately, this is easy to get around:

const currentScript = document.currentScript
ā€‹
function myCallback() {
  console.log(currentScript.src)
}
ā€‹
setTimeout(myCallback, 1000)

By saving a reference to the script file when the code runs synchronously, we are able to reference the document.currentScript property later in our asynchronous code.

Another caveat is that document.currentScript doesn't work in JavaScript modules. That's okay. We can just use the import.meta property there instead.

Internet Explorer

document.currentScript is supported by all modern browsers, but doesn't have support in Internet Explorer. You can still use this snippet to achieve the same effect:

var currentScript;
if (document.currentScript) {
  currentScript = document.currentScript
} else {
  var scripts = document.getElementsByTagName('script')
  currentScript = scripts[scripts.length - 1]
}
console.log('Script located at: ' + currentScript.src)

We will query for all script elements on the page and then grab the last one by its index. With few exceptions, the currently executing script will be the last script element added to the DOM, as any later script elements haven't been loaded yet.

One rare exception where this won't work is if you dynamically append a script within the DOM, such as in the head of the document, after page load. If there were script elements in the body of the HTML document, the last one would be returned instead of the currently executing script that was added later.

The good news is that if you are manually appending scripts to the DOM, you can ensure those dynamically added scripts are being added at the end of the body where this script will successfully identify them in Internet Explorer.