Using jQuery Before It’s Loaded

It’s better to include scripts like jQuery at the end of the BODY, but this makes its methods inaccessible earlier in the page (e.g. inside a WordPress post). What you can do is use a script like the one below to queue DOMReady functions before jQuery loads.

(function (w) {
    if (w.$) // jQuery already loaded, we don't need this script
        return;
    var _funcs = [];
    w.$ = function (f) { // add functions to a queue
        _funcs.push(f);
    };
    w.defer$ = function () { // move the queue to jQuery's DOMReady
        while (f = _funcs.shift())
            $(f);
    };
})(window);

Minified:

Setup

  1. Link to the script in the HEAD or at least before your typical page content area
  2. Link to jQuery at the end of BODY
  3. Below jQuery, include: <script>defer$()</script>

Now in the BODY you can use $(function(){ ... }); to queue up a function as if jQuery were already loaded. And, thanks to the fact that Javascript identifiers are referenced at run-time, you can call any other jQuery functions inside your queued function.

With some modifications you can use this pattern for any library with a similar DOMReady implementation.

1 thoughts on “Using jQuery Before It’s Loaded

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.