How to pass parameters to a Script tag?
Got it. Kind of a hack, but it works pretty nice:
var params = document.body.getElementsByTagName('script');
query = params[0].classList;
var param_a = query[0];
var param_b = query[1];
var param_c = query[2];
I pass the params in the script tag as classes:
<script src="http://path.to/widget.js" class="2 5 4"></script>
This article helped a lot.
What's the simplest script tag with params
If the way the script is executed, depends on how it's called, you can add params like your option 1.
Other ways are:
<script params='{"abc": 123}' src="script.js"></script><!-- params is a non standard, non official attr that the script will read -->
or
<script>var _abc = 123;</script>
<script src="script.js"></script>
or even
<script src="script.js#abc=123"></script>
I have to agree with @outis though: load the same thing for everybody, always, and execute it like you/the client want(s) afterwards.
Passing parameters to JavaScript files
I'd recommend not using global variables if possible. Use a namespace and OOP to pass your arguments through to an object.
This code belongs in file.js:
var MYLIBRARY = MYLIBRARY || (function(){
var _args = {}; // private
return {
init : function(Args) {
_args = Args;
// some other initialising
},
helloWorld : function() {
alert('Hello World! -' + _args[0]);
}
};
}());
And in your html file:
<script type="text/javascript" src="file.js"></script>
<script type="text/javascript">
MYLIBRARY.init(["somevalue", 1, "controlId"]);
MYLIBRARY.helloWorld();
</script>
Pass a variable to Javascript directly from script HTML tag
<script async src="https://example.com/lib.js" site="sitePath"></script>
and:
site = document.currentScript.getAttribute('site'); // sitePath
Related Topics
Sum of Array Object Property Values in New Array of Objects in JavaScript
JavaScript .Queryselector Find <Div> by Innertext
Which Edition of Ecma-262 Does Google Apps Script Support
How to Communicate Between Popup.Js and Background.Js in Chrome Extension
Inject a Script Tag with Remote Src and Wait for It to Execute
Pass Value to Iframe from a Window
Date.Setmonth' Causes the Month to Be Set Too High If 'Date' Is at the End of the Month
Check If Option Is Selected with Jquery, If Not Select a Default
What Are the Actual Uses of Es6 Weakmap
Differencebetween & VS @ and = in Angularjs
Scriptmanager.Registerstartupscript Code Not Working - Why
How to Do Two-Way Filtering in Angularjs
Testing If a Checkbox Is Checked with Jquery
Does Using $This Instead of $(This) Provide a Performance Enhancement
How to Remove Documents Using Node.Js Mongoose