1

Often, when I update a JavaScript or CSS file used by a webpage, I will tack on v=<version>. This helps me track what changes I have made but also forces the browser to get the newest version instead of using cache. Example:

<script src="functions.js?v=1.4"></script>

Is is possible, using JavaScript, to detect any query parameters used? Meaning, could function.js detect that v is 1.4?

steveo225
  • 11,394
  • 16
  • 62
  • 114

2 Answers2

3

There's no a specific method for this, but you can inspect the DOM as usual:

var script = document.querySelector('script[src~="function.js"]');
script.src.replace(/.+?v=/, ''); // that's your version
katspaugh
  • 17,449
  • 11
  • 66
  • 103
  • And then you'll need to apply some helper to get query parameter value you'd like – dentuzhik Feb 28 '14 at 20:16
  • Think this can be approved as the right one. Also it should be tested, whether it could be done from the same script. I think you need a separate one. – dentuzhik Feb 28 '14 at 20:17
  • `document.querySelector('script[src~="function.js"]')` seems to return null for me, although, for the time being, I was able to loop over `document.querySelectorAll('script')` to manually find my file – steveo225 Feb 28 '14 at 21:02
  • @steveo225 Try `src~="functions.js"` (with `s`) instead of `src~="function.js"`. – Oriol Feb 28 '14 at 21:13
  • I did make sure the filename was correct. In actuality, the file isn't even named `functions.js`, that was just an example. Not sure why it reports `null`, but like I said, I brute forced it with `querySelectorAll` – steveo225 Mar 01 '14 at 01:15
0
<script id="file-js" src="functions.js?v=1.4"></script>

Code to find all parameters :

var url = document.getElementById('file-js').src;
url = url.replace(/^.*?\?/, '');
var params = url.split('&');
for(var i in params) {
    var pair = params[i].split('=');
    console.log(pair);
}
B.Asselin
  • 978
  • 10
  • 19