Thursday, October 14, 2010

Dynamically adding jQuery to header only if it hasn't been loaded

Some time ago I did some research on Javascript and some magical, lesser known features that modern javascript libraries leverage to their great advantage.

It's not really all that magical when you get right down to it, but it is really cool.

Take this for instance:

        if(typeof jQuery == 'undefined'){
            var headID = document.getElementsByTagName("head")[0];        
            var jsNode = document.createElement('script');
            jsNode.src = "";

On a partial template that may or may not be included within another template, we don't want to load jQuery twice. The above script checks if jQuery exists, if not then it appends jQuery to the header.

Lets break it down. I live this part:  Javascript works within a framework of code blocks. They are encapsulated within parenthesis (). This serves for nothing else than to isolated it's workings from the code around it. a second set of parenthesis ()() makes the first set of parenthesis self-executing upon page load. This is completely independent of any <body onload=""> type of functionality and is executed inline upon being rendered by the browser. You can have multiple instances. They are executed linearly, synchronously (as far as I understand).

The reason for breaking up the word SCR'+'IPT is because this code is nested within an outer set of <script></script> tags and will end the outer set prematurely and break the page.

There, now I can always reference this post whenever I need to find this code snippet in the future.

That's a wrap.