Pass vars to JavaScript via the SRC attribute

2019-01-02 21:09发布

问题:

In my HTML file I have linked to the JS with:

src="myscript.js?config=true"

Can my JS directly read the value of this var like this?

alert (config);

This does not work, and the FireFox Error Console says "config is not defined". How do I read the vars passed via the src attribute in the JS file? Is it this simple?

回答1:

<script>
var config=true;
</script>
<script src="myscript.js"></script>

You can't pass variables to JS the way you tried. SCRIPT tag does not create a Window object (which has a query string), and it is not server side code.



回答2:

Yes, you can, but you need to know the exact script file name in the script :

var libFileName = 'myscript.js',
    scripts = document.head.getElementsByTagName("script"), 
    i, j, src, parts, basePath, options = {};

for (i = 0; i < scripts.length; i++) {
  src = scripts[i].src;
  if (src.indexOf(libFileName) != -1) {
    parts = src.split('?');
    basePath = parts[0].replace(libFileName, '');
    if (parts[1]) {
      var opt = parts[1].split('&');
      for (j = opt.length-1; j >= 0; --j) {
        var pair = opt[j].split('=');
        options[pair[0]] = pair[1];
      }
    }
    break;
  }
}

You have now an 'options' variable which has the arguments passed. I didn't test it, I changed it a little from http://code.google.com/p/canvas-text/source/browse/trunk/canvas.text.js where it works.



回答3:

You might have seen this done, but really the JS file is being preprocessed server side using PHP or some other language first. The server side code will print/echo the javascript with the variables set. I've seen a scripted ad service do this before, and it made me look into seeing if it can be done with plain ol' js, but it can't.



回答4:

You need to use Javascript to find the src attribute of the script and parse the variables after the '?'. Using the Prototype.js framework, it looks something like this:

var js = /myscript\.js(\?.*)?$/; // regex to match .js

var jsfile = $$('head script[src]').findAll(function(s) {
    return s.src.match(js);
}).each(function(s) {
    var path = s.src.replace(js, ''),
    includes = s.src.match(/\?.*([a-z,]*)/);
    config = (includes ? includes[1].split('=');
    alert(config[1]); // should alert "true" ??
});

My Javascript/RegEx skills are rusty, but that's the general idea. Ripped straight from the scriptaculous.js file!



回答5:

Your script can however locate its own script node and examine the src attribute and extract whatever information you like.

  var scripts = document.getElementsByTagName ('script');
  for (var s, i = scripts.length; i && (s = scripts[--i]);) {
    if ((s = s.getAttribute ('src')) && (s = s.match (/^(.*)myscript.js(\?\s*(.+))?\s*/))) {
      alert ("Parameter string : '" + s[3] + "'");    
      break;
    } 
  }


回答6:

Whether or not this SHOULD be done, is a fair question, but if you want to do it, http://feather.elektrum.org/book/src.html really shows how. Assuming your browser blocks when rendering script tags (currently true, but may not be future proof), the script in question is always the last script on the page up to that point.

Then using some framework and plugin like jQuery and http://plugins.jquery.com/project/parseQuery this becomes pretty trivial. Surprised there's not a plugin for it yet.

Somewhat related is John Resig's degrading script tags, but that runs code AFTER the external script, not as part of the initialization: http://ejohn.org/blog/degrading-script-tags/

Credits: Passing parameters to JavaScript files , Passing parameters to JavaScript files



回答7:

Using global variables is not a so clean or safe solution, instead you can use the data-X attributes, it is cleaner and safer:

<script type="text/javascript" data-parameter_1="value_1" ... src="/js/myfile.js"></script>

From myfile.js you can access the data parameters, for instance with jQuery:

var parameter1 = $('script[src*="myfile.js"]').data('parameter_1');

Obviously "myfile.is" and "parameter_1" have to match in the 2 sources ;)



标签: