Reputation: 46423
Is it possible to pass a variable directly from the HTML tag <script>
:
<script async src="https://example.com/lib.js" site="test.com"></script>
such that lib.js
can access site
like a regular variable?
Upvotes: 18
Views: 1870
Reputation: 382
let me = document.querySelector('script[src$="lib.js"]');
me.getAttribute("site");
In addition to the answers above, this script will let you have more freedom to change the script's file name or path
Upvotes: 0
Reputation: 476
<script async src="https://example.com/lib.js" site="sitePath"></script>
and:
site = document.currentScript.getAttribute('site'); // sitePath
Upvotes: 26
Reputation: 6505
Yes this is possible. Instead of creating a site
attribute we can use the dataset. This is made for custom (data-)attributes.
All you need to do now is give the script an ID and query your data.
HTML:
<script async src="script.js" data-site="test.com" id="myscript"></script>
JS:
const script = document.querySelector("#myscript");
console.log(script.dataset.site);
EDIT: without a querySelector
console.log(document.currentScript.dataset.site);
Upvotes: 9