2

Is it possible to have a javascript link like this (notice the query string):

  <script type = "text/javascript" src = "/js/myScipt.js?v=3"></script>

and then in myScript.js get the value of v using jQuery? A javascript answer is okay too, but jQuery is preferred. Thanks in advance! I searched all over and all I could find were questions pertaining to getting the value of a query string in the URL, but not from it's own link.

John
  • 473
  • 5
  • 20
  • 1
    What is expected result of including `?v=3` at `src` of ` – guest271314 Oct 26 '16 at 01:30
  • 2
    http://stackoverflow.com/questions/5292372/how-to-pass-parameters-to-a-script-tag – react_or_angluar Oct 26 '16 at 01:32
  • Perhaps it uses the value of v in some conditional statement, which produced a different affect depending on what v is. This would be easier than someone editing myScript.js every time to hard code whatever the value of v should be. – John Oct 26 '16 at 01:36
  • @natel thank you, that link was very helpful – John Oct 26 '16 at 01:37

2 Answers2

3
//to set script do some thing like this
var version = 3;
document.write('<script type = "text/javascript" src = "/js/myScipt.js?v='+version+'"></script>');
//or 
$("body").append('<script type = "text/javascript" src = "/js/myScipt.js?v='+version+'"></script>');


//to get v from myscript.js
var getV = document.currentScript.src.split("?v=")[1];
// var getV =  $('script').last().attr("src").split("?v=")[1];
Mamdouh Saeed
  • 2,302
  • 1
  • 9
  • 11
  • Makes sense, but why would you set the script that way instead of just inserting the link directly as in my example in the original post? – John Oct 26 '16 at 01:48
  • No reasons just examples – Mamdouh Saeed Oct 26 '16 at 01:49
  • I thought you were going to say it was a security thing – John Oct 26 '16 at 01:54
  • Actually no reasons may be you need to make src dynamic, thats all – Mamdouh Saeed Oct 26 '16 at 01:59
  • Ah, got it. Makes sense, but in my case there's no need to do that. I was thinking more along the lines of using the script on multiple sites, but don't want it to do quite the same thing on every site . I would rather just pass the script a query string than set the value in each copy of the script on each site, and have 10 different version of the script around.. I marked your answer correct because it was the easiest for me to understand. Thanks! – John Oct 26 '16 at 02:02
  • Glad to help you :) – Mamdouh Saeed Oct 26 '16 at 09:08
1

There is no reason for you to pass information through the link when calling a script. That JavaScript will run after it has been called. There is for sure a better way to do what you are trying to acomplish with this.

Something like this might give you an idea.

 var value;
$("script").each(function(){

var temp = "v=";
If(this.src.indexOf(temp) > -1 )) > -1){

get last digits before "&" if any exist.
And after the index of temp var.
}
});