Query String Aware JavaScript

As developers we know it’s useful to read the query string (everything after the ‘?’ in the URL) to allow for customisations.

However, I didn’t think I could read the query string in the script tag from within the JavaScript – until now.

The Trick

The trick is simple, in your externally loaded script, you read the last DOM element loaded (this script tag that loaded the current script), grab the last DOM element, read the src and there’s your query string.

The Code

// script included using test.js?a=10&z=50
function getLastChild(el) {
  return (el.lastChild && el.lastChild.nodeName != '#text') ? getLastChild(el.lastChild) : el;
}

var query = getLastChild(document.lastChild).getAttribute('src').replace(/.*\?/, '');

The query variable now contains the full query string and can be used to change the result of your script.

I would then pass that in to my getQuery function so I had access to it as an object.

Demo

I’ve created two separate snippets on JS Bin (my new weekend project), one containing the external script code (with getQuery) and one that makes the call:

5 Responses to “Query String Aware JavaScript”

  1. really great work this js bin!

  2. This is the approach that TIBCO General Interface has used for awhile to parse runtime configuration variables.

  3. thanks – great idea

  4. Surely this will become a problem if you’re loading several scripts asynchronously? Example:
    - script tag 1 appended, starts downloading, this is now last child
    - script tag 2 appended, starts downloading, this is now last child
    - script tag 1 finished downloading, thinks it’s script tag 2

    Please correct me if I’m wrong.

  5. @Robert – yep, it’s just for those script tags that are loaded from the original markup.

Leave a Reply
Not required

CODE: Please escape code and wrap in <pre><code>, doing so will automatically syntax highlight