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'; 
5
  • 3
    Possible duplicate of Pass vars to JavaScript via the SRC attribute or Passing parameters to JavaScript files Commented Aug 28, 2014 at 9:22
  • 1
    stackoverflow.com/questions/1343801/… Commented Aug 28, 2014 at 9: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? Commented Aug 28, 2014 at 9: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 Commented Aug 28, 2014 at 9: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 = .... Commented Aug 28, 2014 at 9:37

2 Answers 2

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 } } 
Sign up to request clarification or add additional context in comments.

Comments

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.

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.