18

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?

3
  • 1
    This is not a commonly used pattern. You should probably just allow people to invoke some setup method and pass in actual JavaScript variables. Commented Dec 21, 2020 at 13:55
  • @meagar Yes, I see it's not commonly used. If you want, could you elaborate on why it's not often used, and why invoking a setup is a superior solution, in an answer? Commented Dec 21, 2020 at 13:56
  • 3
    Does this answer your question? How to pass parameters to a Script tag? Commented Dec 21, 2020 at 13:59

3 Answers 3

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

and:

site = document.currentScript.getAttribute('site'); // sitePath
Sign up to request clarification or add additional context in comments.

Comments

9

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);

2 Comments

Interesting solution! I'm being nitpicky: do you think there's a way without asking people using my lib to set an ID to the <script>?
0
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

1 Comment

This is a very broad selector which could return multiple matches.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.