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?
asked Dec 21, 2020 at 13:40
Basj
47.6k113 gold badges468 silver badges819 bronze badges
-
1This is not a commonly used pattern. You should probably just allow people to invoke some setup method and pass in actual JavaScript variables.user229044– user229044 ♦2020年12月21日 13:55:06 +00:00Commented 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?Basj– Basj2020年12月21日 13:56:35 +00:00Commented Dec 21, 2020 at 13:56
-
3Does this answer your question? How to pass parameters to a Script tag?Lain– Lain2020年12月21日 13:59:48 +00:00Commented Dec 21, 2020 at 13:59
3 Answers 3
<script async src="https://example.com/lib.js" site="sitePath"></script>
and:
site = document.currentScript.getAttribute('site'); // sitePath
Basj
47.6k113 gold badges468 silver badges819 bronze badges
answered Dec 21, 2020 at 13:51
Olaru Alina
4764 silver badges9 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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);
answered Dec 21, 2020 at 13:48
StackByMe
6,57522 silver badges31 bronze badges
2 Comments
Basj
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>?Ivar
@Basj
document.currentScript 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
JavaScript
This is a very broad selector which could return multiple matches.
default