Adding in the brand new, working, IE DOM Ready code. Plus I made it such that if you bind a ready() function after the DOM has loaded, it will fire the function instantly.

This commit is contained in:
John Resig 2006-06-14 20:05:06 +00:00
parent 25f5af1bcb
commit ba7ebaf70b

View File

@ -41,8 +41,12 @@ $.fn.hover = function(f,g) {
}); });
}; };
$.$$isReady = false;
$.$$ready = [];
// Handle when the DOM is ready // Handle when the DOM is ready
$.ready = function(isFinal) { $.ready = function() {
$.$$isReady = true;
if ( $.$$ready ) { if ( $.$$ready ) {
for ( var i = 0; i < $.$$ready.length; i++ ) { for ( var i = 0; i < $.$$ready.length; i++ ) {
$.apply( document, $.$$ready[i] ); $.apply( document, $.$$ready[i] );
@ -51,27 +55,28 @@ $.ready = function(isFinal) {
} }
}; };
// Based off of:
// http://linguiste.org/projects/behaviour-DOMContentLoaded/example.html
// If Mozilla is used // If Mozilla is used
if ( $.browser == "mozilla" ) { if ( $.browser == "mozilla" ) {
// Use the handy event callback // Use the handy event callback
document.addEventListener( "DOMContentLoaded", $.ready, null ); document.addEventListener( "DOMContentLoaded", $.ready, null );
// If IE is used // If IE is used, use the excellent hack by Matthias Miller
// http://www.outofhanwell.com/blog/index.php?title=the_window_onload_problem_revisited
} else if ( $.browser == "msie" ) { } else if ( $.browser == "msie" ) {
// Only works if you document.write() it
document.write('<script id="__ie_init" defer="true" ' +
'src="javascript:void 0"><\/script>');
// Use the defer script hack // Use the defer script hack
var script = document.createElement('script'); var script = document.getElementById('__ie_init');
//script.type = 'text/javascript';
script.src = 'javascript:void 0';
script.defer = true;
script.onreadystatechange = function() { script.onreadystatechange = function() {
if ( this.readyState == 'loading' ) { if ( this.readyState == 'complete' ) {
$.ready(); $.ready();
} }
}; };
document.getElementsByTagName('head')[0].appendChild(script);
// Clear from memory
script = null; script = null;
// If Safari or Opera is used // If Safari or Opera is used
@ -89,21 +94,23 @@ if ( $.browser == "mozilla" ) {
} }
// A fallback, that will always work, just in case // A fallback, that will always work, just in case
$.event.add( window, "load", function(){ $.event.add( window, "load", $.ready );
$.ready(true);
});
/** /**
* Bind a function to fire when the DOM is ready. * Bind a function to fire when the DOM is ready.
*/ */
$.fn.ready = function(f) { $.fn.ready = function(f) {
return this.each(function(){ if ( $.$$isReady ) {
$.apply( document, f );
} else {
if ( ! $.$$ready ) { if ( ! $.$$ready ) {
$.$$ready = []; $.$$ready = [];
} }
$.$$ready.push( f ); $.$$ready.push( f );
}); }
return this;
}; };
$.fn.toggle = function(a,b) { $.fn.toggle = function(a,b) {