Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing parameters to JavaScript files

Often I will have a JavaScript file that I want to use which requires certain variables be defined in my web page.

So the code is something like this:

<script type="text/javascript" src="file.js"></script> <script type="text/javascript">    var obj1 = "somevalue"; </script> 

But what I want to do is:

<script type="text/javascript"       src="file.js?obj1=somevalue&obj2=someothervalue"></script> 

I tried different methods and the best one yet is to parse the query string like this:

var scriptSrc = document.getElementById("myscript").src.toLowerCase(); 

And then search for my values.

I wonder if there is another way to do this without building a function to parse my string.

Do you all know other methods?

like image 460
RaduM Avatar asked Feb 03 '10 09:02

RaduM


People also ask

How do you pass variables between JavaScript files?

You cannot pass variables from one js file to the other Javascript variables are stateless so they wont be retained. If you are using . Net then you can make use of Session variables to solve this purpose. If you use MVC you can go for viewbag or viewdata.

Can you pass a variable to JavaScript?

In Pass by Reference, a function is called by directly passing the reference/address of the variable as the argument. Changing the argument inside the function affects the variable passed from outside the function. In Javascript objects and arrays are passed by reference.

What is parameter passing in JavaScript?

Arguments are Passed by Value The parameters, in a function call, are the function's arguments. JavaScript arguments are passed by value: The function only gets to know the values, not the argument's locations. If a function changes an argument's value, it does not change the parameter's original value.

How do you pass a value in a script?

Arguments can be passed to the script when it is executed, by writing them as a space-delimited list following the script file name. Inside the script, the $1 variable references the first argument in the command line, $2 the second argument and so forth. The variable $0 references to the current script.


1 Answers

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> 
like image 196
Naeem Sarfraz Avatar answered Sep 19 '22 02:09

Naeem Sarfraz