Friday, June 8, 2012

$(document).ready equivalent without jQuery


I have a script that uses $(document).ready, but doesn't use anything else from jQuery. I'd like to lighten it up by removing the jquery dependency.



How can I implement that functionality without it? It does more than window.onload.


Source: Tips4all

3 comments:

  1. What about js code that is placed in a script tag at the bottom of the document, say after the closing body tag? Will that get executed at the correct time? (it seems to for me)

    Admittedly this might not suit everyone's purposes since it requires changing the html file rather than just doing something in the js file a la document.ready, but still....

    ReplyDelete
  2. I was recently using this for a mobile site. This is John Resig's simplified version from "Pro JavaScript Techniques". It depends on addEvent.

    var ready = ( function () {
    function ready( f ) {
    if( ready.done ) return f();

    if( ready.timer ) {
    ready.ready.push(f);
    } else {
    addEvent( window, "load", isDOMReady );
    ready.ready = [ f ];
    ready.timer = setInterval(isDOMReady, 13);
    }
    };

    function isDOMReady() {
    if( ready.done ) return false;

    if( document && document.getElementsByTagName && document.getElementById && document.body ) {
    clearInterval( ready.timer );
    ready.timer = null;
    for( var i = 0; i < ready.ready.length; i++ ) {
    ready.ready[i]();
    }
    ready.ready = null;
    ready.done = true;
    }
    }

    return ready;
    })();

    ReplyDelete
  3. the ready function in jQuery does a number of things. Frankly, I don't see that point of replacing it unless you have amazingly small output from your website. jquery is a pretty tiny library, and it handles all sorts of cross-browser things you'll need later.

    Anyway, there's little point in posting it here, just open up jquery and look at the bindReady method.

    It starts by calling either document.addEventListener("DOMContentLoaded") or document.attachEvent('onreadystatechange') depending on the event model, and goes on from there.

    ReplyDelete