Scott Donnelly

yepnope and jQuery - fix for $(document).ready calls

I recently added the fantastic yepnope.js to a site in order to give it a bit of a speedup. The site already had jQuery, including a few calls to $(document).ready() across a few different files. As anybody who has tried this knows, this breaks your $(document).ready() calls. jQuery is not loaded at the point that the browser tries to execute the document ready call, so the browser gives an error, complaining that $ is undefined. Here is my solution.

First, add this in your <head>, before yepnope and anything that could use jQuery. This sets up a placeholder that stores any calls to $(document).ready() in an array called docready.

var docready=[],$=function(o){function r(fn){docready.push(fn);}if(typeof o === 'function') r(o);return{ready: r}};

Secondly, in your yepnope call to load jQuery, change the “complete” call like so:

yepnope({
load: ‘//ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js’,
callback: function (url, result, key) {
if (!window.jQuery) yepnope(‘/js/jquery.min.js’);
},
complete: function() {
$ = jQuery;
jQuery(document).ready(function() {
for(n in docready) docreadyn;
});
}
});

So now, once jQuery has loaded, $ is reassigned from our placeholder to jQuery, and the stored $(document).ready() calls are iterated through and executed once ready fires. Sweet!

Edit: Updated with new, more concise, complete callback.

Edit 2: Updated to handle $(function() {}) style invocations, thanks to Chris Jones