Posted in Code Snippets, Javascript

Using query string in script tag

It is possible to send query string to an external JavaScript file like this:

< script src="scripts.js?version=123"></script>

I have already posted on how we can get the value of a field from query string in URL using JavaScript can be found here. Similarly, getting value of a field from query string in src attribute of script tag is discussed below:

Say, index.html holds:

< script src="scripts.js?version=123"></script>
var version = getURLParameter("version");

Following scripts are needed to be present in script.js

//Get the URL from the calling script
var scriptSource = (function(scripts) {
    var scripts = document.getElementsByTagName('script'),
           script = scripts[scripts.length - 1];
   if (script.getAttribute.length !== undefined) {
      return script.src
   return script.getAttribute('src', -1)

//Get the query string
function getURLParameter(name) {
    return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)
                              [1].replace(/\+/g, '%20'))||null

Running this script will result in variable version holding the value 123.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s