0

I am including a javascript file in my web page like as follows,

 <script src="my_script.js?mytestvalue" type='text/javascript' ></script>

Is possible to take the value mytestvalue to a variable in my javascript file my_script.js ?

ie

 var my_value=somefunction();
 //my_value = 'mytestvalue';
Shijin TR
  • 7,516
  • 10
  • 55
  • 122
  • 3
    Possible duplicate of [Pass vars to JavaScript via the SRC attribute](http://stackoverflow.com/q/1017424/851811) or [Passing parameters to JavaScript files](http://stackoverflow.com/q/2190801/851811) – Xavi López Aug 28 '14 at 09:22
  • 1
    http://stackoverflow.com/questions/1343801/pass-variable-to-external-js-file – trainoasis Aug 28 '14 at 09:23
  • 2
    it's hard to see any reason to do this. what's that you're really trying to achieve here? why do you want to do this? – Karoly Horvath Aug 28 '14 at 09:25
  • @KarolyHorvath , I am trying to avoid caching that js file in browser,each time this value will be passed dynamically,I need to get that value,and do some execution based on that value – Shijin TR Aug 28 '14 at 09:28
  • @Shin: this is a way to avoid caching. but it's unrelated. using this value is an entirely different issue. just use `var config = ....` – Karoly Horvath Aug 28 '14 at 09:37

2 Answers2

1

You can get all scripts with document.getElementsByTagName("script") and loop trough all to find my_script.js.

When the right script is found you pick the value from the src.

window.onload = function() {
   var scripts = document.getElementsByTagName("script"); //All script
   for(i = 0; i < scripts.length; i++) {
      var script = scripts[i].src; //The src
      if(script.substring(script.lastIndexOf("/") + 1, script.indexOf("?")) == 
              "my_script.js") //If script src is my_script.js
           var my_value = script.substring(script.indexOf("?")+1); //Get my_value
           //Do something with my value
   }
}
Afsa
  • 2,025
  • 1
  • 16
  • 19
0

You can put this to the my_script.js:

var scripts = document.getElementsByTagName('script'),
    currentScript = scripts[scripts.length - 1],
    searchString = currentScript.src.split('?')[1];

The last loaded script (i.e. current running script) is in the last index of document.getElementsByTagName('script'), then just extract the search string from the src.

Use of this might make sense if you'll create the script tag dynamically. In a case of a hardcoded tag it's simpler to use a global variable.

Teemu
  • 22,918
  • 7
  • 53
  • 106