18

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

9 Answers 9

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

Sign up to request clarification or add additional context in comments.

4 Comments

Good alternative, though it does not answer my question :)
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"
Although, the src attr can point to a php (or any other server side tech) and accomplish this.
Security people and CSP seem to want us never to us inline JavaScript.
6

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.

2 Comments

I'm struggling to think of a real-world use case where this would be more beneficial than Itay Moav's answer.
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.
4

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.

2 Comments

This is also how JSONP (en.wikipedia.org/wiki/JSONP#JSONP) works. You pass the name of a function, and the server echoes it in the body.
Indeed, as JSONP is handled by a server-side language such as PHP or ASP.
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!

Comments

4

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 ;)

Update 2024

under certain conditions, you can access it directly from the JS inside the script:

let parameter_1=document.currentScript.dataset.parameter_1;

from the reference :

It's important to note that this will not reference the element if the code in the script is being called as a callback or event handler; it will only reference the element while it's initially being processed.

1 Comment

Works like a charm! perfect solve my problem that I've was stucked!
1

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;
    } 
  }

2 Comments

Wouldn't it be much simpler to give the script tag an ID and in it use document.getElementById ?
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.
0

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

Comments

0

You can do that with a single line code:

new URL($('script').filter((a, b, c) => b.src.includes('myScript.js'))[0].src).searchParams.get("config")

Comments

0

It's simpler if you pass arguments without names, just like function calls.

In HTML:

<script src="abc.js" data-args="a,b"></script>

Then, in JavaScript:

const args=document.currentScript.dataset.args.split(',');

Now args contains the array ['a','b'].

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.