Hello i have this example
<script src="https://example.com/init.js?v=1589383111"></script>
How i get Argument v inside the init.js script
init.js script
var version = v; // argument from the src itself
Hello i have this example
<script src="https://example.com/init.js?v=1589383111"></script>
How i get Argument v inside the init.js script
init.js script
var version = v; // argument from the src itself
You can access the current script tag with document.currentScript
. Then its a simple matter of extracting the src
attribute, and parsing it as a URL.
<!-- _src is used simply for demo purpose. You can't have a src attribute on a script tag with a body -->
<script _src="https://example.com/init.js?v=1589383111">
const self = document.currentScript;
const v = new URLSearchParams(
new URL(self.getAttribute('_src')).search,
).get('v');
console.log(v);
</script>
I'd consider putting the version in a data attribute on the backend, along with an ID. Then you can access them from the DOM:
<script src="https://example.com/init.js?v=1589383111"
data-version="1589383111"
id="importantScript"></script>
Now you can get the value of that attribute:
const version = document.getElementById('importantScript').getAttribute('data-version');
From within the script:
const curScriptElement = document.currentScript;
const queryParams = new URLSearchParams(new URL(curScriptElement.src).search);
const version = queryParams.get('v');
console.log('version is', version);
See demo: https://plnkr.co/edit/vd02AYWHnJhY6eu1
In this case, mind the browser support (IE specifically):
look at URL
and URLSearchParams
-
const u =
new URL('https://example.com/init.js?v=1589383111')
const s =
new URLSearchParams(u.search)
console.log(s.get("v"))
// 1589383111