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:
I live in the sometimes sunny Brighton (it's in the south of the UK, for those across the pond). The south coast is definitely my favourite place to be, but I spent some time on the outskirts of London whilst at University. I'm starting to focus on my own company Left Logic. It's a web development company with strong focus in usability, accessibility, clean design and powerful bespoke applications. Remy is a DZone MVB and is not an employee of DZone and has posted 9 posts at DZone. You can read more from them at their website.
- Login or register to post comments
- 2393 reads
- Printer-friendly version
(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)









