Skip to content

Instantly share code, notes, and snippets.

@cowboy
Forked from ralphholzmann/jQuery immediate ready.js
Created November 5, 2010 16:32
Show Gist options
  • Save cowboy/664405 to your computer and use it in GitHub Desktop.
Save cowboy/664405 to your computer and use it in GitHub Desktop.
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
Copy link
Author

cowboy commented Nov 5, 2010

Here's an example

@kflorence
Copy link

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

@cowboy
Copy link
Author

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