views:

722

answers:

5

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?

+5  A: 
<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.

Itay Moav
Good alternative, though it does not answer my question :)
Jenko
Yes it does: Question "Can my JS directly read the value of this var like this?" Answer "You can't passe variables to JS the way you tried"
Benjol
A: 

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.

Andy E
This is also how JSONP (http://en.wikipedia.org/wiki/JSONP#JSONP) works. You pass the name of a function, and the server echoes it in the body.
Matthew Flaschen
Indeed, as JSONP is handled by a server-side language such as PHP or ASP.
Andy E
+1  A: 

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.

Fabien Ménager
I'm struggling to think of a real-world use case where this would be more beneficial than Itay Moav's answer.
Andy E
In order to make a script easier to integrate. Personnaly I find it easier to pass a few http parameters (which aren't really ones) than having to declare a few variables in another script tag.
Fabien Ménager
+2  A: 

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!

Barry Gallagher
+1 for beating me to it, I had just pasted that :(
karim79
+1  A: 

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;
    } 
  }
Hans B PUFAL
Wouldn't it be much simpler to give the script tag an ID and in it use document.getElementById ?
Itay Moav
Yes if you are the author of both the script and the web page calling it. My code fragment came from a generic library file and I do not want its users to have to use an id with the subsequent issues if it were specified incorrectly.
Hans B PUFAL