6

Pretty straightforward, I've got a JS script that's included on many different sites and needs to have parameters passed to it.

It would be useful if those could be passed via the URL, eg:

<script type="text/javascript" src="http://path.to/script.js?var1=something&var2=somethingelse"></script> 

Yes, you can still pre-populate variables, in a separate script tag, but it's a smidge messy and less easy to pass around:

<script type="text/javascript">var1=something; var2=somethingelse</script> <script type="text/javascript" src="http://path.to/script.js"></script> 
1

4 Answers 4

4

Yep. Added bonus: I convert the query string parameters into a more usable javascript hash.

HTML:

<script src="script.js?var1=something&var2=somethingelse" type="text/javascript"></script> 

script.js:

var scriptSource = (function() { var scripts = document.getElementsByTagName('script'); return scripts[scripts.length - 1].src }()); var params = parseQueryString(scriptSource.split('?')[1]); params.var1; // 'something' params.var2; // 'somethingelse' // Utility function to convert "a=b&c=d" into { a:'b', c:'d' } function parseQueryString(queryString) { var params = {}; if (queryString) { var keyValues = queryString.split('&'); for (var i=0; i < keyValues.length; i++) { var pair = keyValues[i].split('='); params[pair[0]] = pair[1]; } } return params; } 
Sign up to request clarification or add additional context in comments.

3 Comments

Really good approach, but it requires spooling through the completed DOM which may not be reliable.
@Paul: no spooling here. The DOM does not have to be "completed" for document.getElementsByTagName to work.
How is this working with async/defer attribute ? is scriptSource() function reliable written like that ?
2

This method should only be used if the varaibles would determine what JavaScript code was loaded (e.g., with the request being processed by PHP, dynamically building the JS file).

If you want to pass information to JavaScript code, use functions or variables in the code after it is loaded.

Comments

1

error.fileName will tell you the file that a script is from (not sure if it works in every browser; I've tested it in Firefox & Opera)

var filename = (new Error).fileName; 

1 Comment

This is really close, and given IE being... well, IE, I'm 90% sure there's a browser specific equivalent to this.
0

In order to do something like that you'd need to use a server side language to render the JS for you.

I wouldn't recommend it.

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.