Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass vars to JavaScript via the SRC attribute

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?

like image 701
Robin Rodricks Avatar asked Jun 19 '09 11:06

Robin Rodricks


People also ask

What is src used for in JavaScript?

The src attribute specifies the URL of an external script file. If you want to run the same JavaScript on several pages in a web site, you should create an external JavaScript file, instead of writing the same script over and over again.

What is an src attribute?

The src attribute identifies an image by a URL. The image defined by the URL is retrieved by the browser and inserted into the document when the page loads.

How do you pass variables between HTML and JavaScript?

There are two ways to pass variables between web pages. The first method is to use sessionStorage, or localStorage. The second method is to use a query string with the URL.

Is src an attribute or property?

Definition and Usage. The src attribute specifies the location (URL) of the external resource.


2 Answers

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

like image 81
Itay Moav -Malimovka Avatar answered Oct 21 '22 01:10

Itay Moav -Malimovka


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.

like image 36
Fabien Ménager Avatar answered Oct 21 '22 01:10

Fabien Ménager