简体   繁体   中英

How can i use script parameters into my js file?

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?

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".

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>

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.currentScript does not work on IE.

For more info check this out .

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);
}();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM