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