|
Passing variables to js files inline |
Ever wanted to pass a variables to a javascript file within the code?
You can declare JavaScript variables globally, but in this case a non technical person was editing the sites code base, so getting them to construct
JavaScript variables was going to be an issue. How about passing them through within the script tag?
Construct your Javascript script code as usual, but append your value on the end, as per below. Also give the script tag an id value.
Next inside the JavaScript file read the src attributes using JQuery and the id of the script tag. Below I've split the returned string at the '?'
character and created a array out of it. Pick up the first value (not the zero value) and it will give you the text string after the question mark.
You could pass many values like this, and use the split() method to turn them into Arrays and loop through them.
2 scriptsrc = scriptsrc.split('?');
3 scriptsrc = scriptsrc[1];
4 alert('scriptsrc = ' + scriptsrc);