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?
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?
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);
<script>?document.currentScriptlet 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