Pass vars to JavaScript via the SRC attribute

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.


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.


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!


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