Sunday, September 30, 2012

Queue up jQuery requests before it is loaded

If you are loading jQuery just before the closing body tag (if not, stop and read this now), you may be wondering how you can use jQuery before it has been loaded on your page above. Maybe it forced you find some crazy script ordering scheme or maybe you just gave up and included it somewhere else in the body or even in the head.

In a CMS world, each widgets could emit javascript that relies on jQuery existing on the page, but since it isn't loaded until just before the closing body tag, we need a way to fake a reference to jQuery and queue up the requests temporarily until jQuery has been loaded.

I came across this post that seemed to do exactly what we needed. Before jQuery is loaded, the script will queue the jQuery functions calls. Once loaded, the functions are dequeued and executed. Hooking up the script is simple and only involves adding a few small scripts to your page. 

First you have to add an inline script to your head tag. The script will create a fake $ reference on the window if jQuery hasn't yet loaded which pushes each function onto an array. It then defines a new function that will be used to execute each function after jQuery eventually loads.

<script type="text/javascript">
(function (a) {
 if (a.$ || a.jQuery) return;
 var b = [];
 a.$ = function (c) { b.push(c) };
 a.defer$ = function () { while (f = b.shift()) $(f) } }

Next include jQuery just before the closing body tag.
<script type="text/javascript" src="/scripts/jquery.min.js">

Finally, after the jQuery include, call the defer function that we defined in the header. This will loop through each function that was deferred and execute them now that jQuery has been loaded.

<script type="text/javascript">

This is a pretty cool trick, and while I can't take credit for it, I wanted to put the information out there for others to learn from.


No comments:

Post a Comment