javascriptparameter-passing

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?


Solution

  • 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>