Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Bind DOM ready event handlers before jQuery is loaded
// Create a "fake" jQuery function that accepts function arguments to be
// queued as DOM ready callbacks.
(function(window){
var fake = window.jQuery = window.$ = function( fn ) {
if ( Object.prototype.toString.call( fn ) === '[object Function]' ) {
fake.queue.push( fn );
}
};
fake.queue = [];
})(window);
$(function(){
console.log(1);
});
$(function(){
console.log(2);
});
// LOAD JQUERY HERE
$(function(){ // don't do this yet!
console.log(3);
});
// Copy all previously fake-queued DOM ready callbacks into jQuery's
// internal queue.
(function( window, $ ){
$.map( window.$.queue, $ );
window.$ = $;
})( window, jQuery.noConflict() );
$(function(){
console.log(4);
});
// ON DOM READY, CONSOLE LOGS 3 1 2 4
//
// (Obviously, you don't want to bind more events to DOM ready until
// you've executed the queue copy code, that why #3 fires first)
@cowboy

This comment has been minimized.

Copy link
Owner Author

@cowboy cowboy commented Nov 5, 2010

Here's an example

@kflorence

This comment has been minimized.

Copy link

@kflorence kflorence commented Nov 5, 2010

Got a little parse error there: http://jsfiddle.net/7WYQ5/1/

@cowboy

This comment has been minimized.

Copy link
Owner Author

@cowboy cowboy commented Nov 5, 2010

Oops! I fixed my original fiddle, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment