TopUp is one of the more popular so-called "lightbox" libraries that allows you to create Web 2.0 popups for tasks such as viewing full resolution images and playing videos. It works like this: Instead of opening a new browser window, like traditional popups do, TopUp uses Javascript to modify the webpage's DOM and display a popup window inside the webpage. This creates a more fluent user experience because it doesn't push the user away from the webpage they're currently viewing, like traditional popups tend to do.
I was reading the library's documentation and noticed that you can pass configuration settings via query string parameters in the URL to the Javascript file. For example, to enable "fast mode" (a setting that improves support for IE 6 and 7), you would import the TopUp script into your page like so:
<script type="text/javascript" src="path/to/top_up-min.js?fast_mode=1"> </script>
The question I asked myself was, "How are they passing query string parameters into a Javascript file?" If top_up-min.js was really a server-side script that returned Javascript code, then I could understand. But it's an ordinary, plain-text .js file! The file can't be aware of its own URL, so it can't see the parameters!
I opened up the source code to have a look. The author queries the DOM to get a reference to the <script> element that imported the file, and then parses the element's src attribute to get the query string parameters. Pretty clever!
But how does he get a reference to the <script> element? There's nothing unique about this element that you can use to pull it out from the DOM. No unique ID. No specially-named class attribute. How does he do it? What he does is he adds a dummy element to the DOM as soon as the script loads. This guarantees that the dummy element will be added immediately after the <script> element, so he can just get the dummy element's previous sibling and wham...you've got your <script> node.
var scriptElement = (function deriveScriptElement() {
var id = "tu_dummy_script";
document.write('<script id="' + id + '"></script>');
var dummyScript = document.getElementById(id);
var element = dummyScript.previousSibling;
dummyScript.parentNode.removeChild(dummyScript);
return element;
}());
Some people say that programming is not a skill that requires creativity. I would ask these people to look at this code sample and tell me that it's not creative!


0 comments:
Post a Comment