Basj
Basj

Reputation: 46423

Pass a variable to Javascript directly from <script> HTML tag

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

Answers (3)

nourhomsi
nourhomsi

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

Olaru Alina
Olaru Alina

Reputation: 476

<script async src="https://example.com/lib.js" site="sitePath"></script>

and:

site = document.currentScript.getAttribute('site'); // sitePath

Upvotes: 26

Reyno
Reyno

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

Related Questions