Skip to content
Dec 20 / Scotty

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(){return{ready:function(fn){docready.push(fn)}}};

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) docready[n]();
		});
	}
});

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.

Popularity: 4% [?]

Leave a Comment