How to Pass Parameters to a Script Tag

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



Leave a reply



Submit