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
- Link to the script in the HEAD or at least before your typical page content area
- Link to jQuery at the end of BODY
- 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.
Check out my little js lib do to exact that thing :)
https://github.com/Yorkii/wait-for