0

I have this script code:

<script src="http://example.com/embed.js?q=123&parameter1=450&parameter2=300"></script>

How can i get the values of q(123)and parameter1(450) and parameter2(300) and use them into embed.js file? I want to make conditions into my embed.js by using these values. How can i achieve that?

cos nik
  • 386
  • 2
  • 14
  • Possible duplicate of [Passing parameters to JavaScript files](http://stackoverflow.com/questions/2190801/passing-parameters-to-javascript-files) – Hacketo Feb 22 '16 at 10:40
  • Possible duplicate of [How to pass parameters to a Script tag?](http://stackoverflow.com/questions/5292372/how-to-pass-parameters-to-a-script-tag) – Jarno Lonardi Feb 22 '16 at 10:48

4 Answers4

1

Give the script element and ID attribute like this:

<script id="embed-script" src="http://example.com/embed.js?q=123&parameter1=450&parameter2=300"></script>

Javascript:

var url = document.getElementById('embed-script');

function parseGet(val) {
var result = "",
    tmp = [];
var items = url.src.split("?")[1].split('&');

for (var index = 0; index < items.length; index++) {
    tmp = items[index].split("=");
    if (tmp[0] === val)
        result = decodeURIComponent(tmp[1]);
}

return result;
}

Get the values like this, in embed.js:

var value1 = parseGet('q');

value1 should then be "123".

Darko Riđić
  • 459
  • 3
  • 18
0

I think you can't,but you can declare all param before required your js file same as:

<script type="text/javascript">
    var q = 123;
    var parameter1 = 450;
    var parameter2 = 300;
  </script>
  <script src="http://example.com/embed.js"></script>
dieuhd
  • 1,316
  • 1
  • 9
  • 22
0

You could place the parameters in attributes of the <script> tag.

<script src="http://example.com/embed.js" q="123" parameter1="450" parameter2="300"></script>

You can access these parameters in embed.js with

document.currentScript.getAttribute('q');
document.currentScript.getAttribute('parameter1');
document.currentScript.getAttribute('parameter2');

Note: document.currentScriptdoes not work on IE.

For more info check this out.

Jarno Lonardi
  • 303
  • 1
  • 7
0

You can access script tag as the last script tag if ask for it without waiting for document load.

~function() {
  var s = document.querySelectorAll("script");
  s = s[s.length-1];
  console.log(s.src);
}();
Qwertiy
  • 19,681
  • 15
  • 61
  • 128