Skip to content

Instantly share code, notes, and snippets.

@debjitbis08
Created September 25, 2012 09:17
Show Gist options
  • Select an option

  • Save debjitbis08/3780804 to your computer and use it in GitHub Desktop.

Select an option

Save debjitbis08/3780804 to your computer and use it in GitHub Desktop.

Revisions

  1. Debjit Biswas created this gist Sep 25, 2012.
    75 changes: 75 additions & 0 deletions bindReady.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,75 @@
    var bindReady = function (d) {

    function callback() {
    if (this.isReady) {
    return;
    }
    // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
    if ( !document.body ) {
    return setTimeout( callback, 1 );
    }

    this.isReady = true;

    d();
    }

    var DOMContentLoaded = function() {
    if ( document.addEventListener ) {
    document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
    callback();
    } else if ( document.readyState === "complete" ) {
    // we're here because readyState === "complete" in oldIE
    // which is good enough for us to call the dom ready!
    document.detachEvent( "onreadystatechange", DOMContentLoaded );
    callback();
    }
    };

    if ( document.readyState === "complete" ) {
    // Handle it asynchronously to allow scripts the opportunity to delay ready
    setTimeout( callback, 1 );

    // Standards-based browsers support DOMContentLoaded
    } else if ( document.addEventListener ) {
    // Use the handy event callback
    document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );

    // A fallback to window.onload, that will always work
    window.addEventListener( "load", callback, false );

    // If IE event model is used
    } else {
    // Ensure firing before onload, maybe late but safe also for iframes
    document.attachEvent( "onreadystatechange", DOMContentLoaded );

    // A fallback to window.onload, that will always work
    window.attachEvent( "onload", callback );

    // If IE and not a frame
    // continually check to see if the document is ready
    var top = false;

    try {
    top = window.frameElement === null && document.documentElement;
    } catch(e) {}

    if ( top && top.doScroll ) {
    (function doScrollCheck() {
    if ( !this.isReady ) {

    try {
    // Use the trick by Diego Perini
    // http://javascript.nwbox.com/IEContentLoaded/
    top.doScroll("left");
    } catch(e) {
    return setTimeout( doScrollCheck, 50 );
    }

    // and execute any waiting functions
    callback();
    }
    })();
    }
    }
    };