Is it possible for a js function to figure out the file path of its code ? At runtime.
Ex.
<html><head><script src="/js/version-3.2.1/myfile.js" /><head>...</html>
/js/version-3.2.1/myfile.js
JavaScript
x
4
1
const scriptPath = '/js/version-3.2.1/myfile.js' // how do I get this dynamically?:
2
const version = scriptPath.split('-')[1].split('/')[0];
3
console.log("the version is " + version)
4
Advertisement
Answer
You can use document.currentScript
:
The
Document.currentScript
property returns the<script>
element whose script is currently being processed and isn’t a JavaScript module. (For modules useimport.meta
instead.)It’s important to note that this will not reference the
<script>
element if the code in the script is being called as a callback or event handler; it will only reference the element while it’s initially being processed.
JavaScript
1
4
1
const scriptPath = document.currentScript.src
2
// or
3
const scriptPath = document.currentScript.getAttribute('src')
4