Passing parameters to JavaScript files

2019-01-01 10:00发布

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?

12条回答
旧时光的记忆
2楼-- · 2019-01-01 10:20

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>
查看更多
骚的不知所云
3楼-- · 2019-01-01 10:21

Another idea I came across was assigning an “id” to the element and passing the arguments as data-* attributes. The resulting tag would look something like this:

<script id="helper" data-name="helper" src="helper.js"></script>

The script could then use the id to programmatically locate itself and parse the arguments. Given the previous tag, the name could be retrieved like this:

var name = document.getElementById("helper").getAttribute("data-name");

we get name = helper

查看更多
还给你的自由
4楼-- · 2019-01-01 10:22

It's not valid html (I don't think) but it seems to work if you create a custom attribute for the script tag in your webpage:

<script id="myScript" myCustomAttribute="some value" ....>

Then access the custom attribute in the javascript:

var myVar = document.getElementById( "myScript" ).getAttribute( "myCustomAttribute" );

Not sure if this is better or worse than parsing the script source string.

查看更多
步步皆殇っ
5楼-- · 2019-01-01 10:24

You can pass parameters with arbitrary attributes. This works in all recent browsers.

<script type="text/javascript" data-my_var_1="some_val_1" data-my_var_2="some_val_2" src="/js/somefile.js"></script>

Inside somefile.js you can get passed variables values this way:

........

var this_js_script = $('script[src*=somefile]'); // or better regexp to get the file name..

var my_var_1 = this_js_script.attr('data-my_var_1');   
if (typeof my_var_1 === "undefined" ) {
   var my_var_1 = 'some_default_value';
}
alert(my_var_1); // to view the variable value

var my_var_2 = this_js_script.attr('data-my_var_2');   
if (typeof my_var_2 === "undefined" ) {
   var my_var_2 = 'some_default_value';
}
alert(my_var_2); // to view the variable value

...etc...

查看更多
明月照影归
6楼-- · 2019-01-01 10:24

might be very simple

for example

<script src="js/myscript.js?id=123"></script>
<script>
    var queryString = $("script[src*='js/myscript.js']").attr('src').split('?')[1];
</script>

You can then convert query string into json like below

var json = $.parseJSON('{"' 
            + queryString.replace(/&/g, '","').replace(/=/g, '":"') 
            + '"}');

and then can use like

console.log(json.id);
查看更多
初与友歌
7楼-- · 2019-01-01 10:26

No, you cant really do this by adding variables to the querystring portion of the JS file URL. If its writing the portion of code to parse the string that bothers you, perhaps another way would be to json encode your variables and put them in something like the rel attribute of the tag? I don't know how valid this is in terms of HTML validation, if thats something you're very worried about. Then you just need to find the rel attribute of the script and then json_decode that.

eg

<script type='text/javascript' src='file.js' rel='{"myvar":"somevalue","anothervar":"anothervalue"}'></script>
查看更多
登录 后发表回答