It is always better to include scripts in the bottom of the page to avoid blocking.
However, sometimes you need to use some jQuery code before you load the script. Here is a solution to do so
- Include the following in the header
<script>
(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);
</script>
- after loading the jQuery script in the bottom of the page add the following code
<script>defer$()</script>
After doing the above, in the body you can use $(function(){ ... }); . This will queue up a function as if jQuery was already loaded.
Originally found on http://www.mrclay.org/2010/11/14/using-jquery-before-its-loaded/