> From: Kean
> 
> No, I don't take that as an insult.

I was worried needlessly, then. :-)

> I was just wondering how document ready was coded so it 
> really was just a hypothetical question.

Well, there is the source code. :-)

http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.js

Just search for "ready" and you'll find the relevant bits. It's not very
complicated, but it does have a lot more overhead than the simplified
version I posted in my previous reply.

In particular, here's the code that adds the function to the readyList
array:

    jQuery.readyList.push( function() { return fn.call(this, jQuery); } );

Note that it wraps each of your callback functions in *another* function,
just so it can provide the calling sequence described in the docs:

http://docs.jquery.com/Events/ready

And here's the code that calls the functions:

    if ( jQuery.readyList ) {
        // Execute all of them
        jQuery.each( jQuery.readyList, function(){
            this.call( document );
        });

        // Reset the list of functions
        jQuery.readyList = null;
    }

Note that this code uses *yet another* wrapper function. So that's three
function calls for each ready function.

Compare that with the code I posted which makes only a single function call
for each ready function:

    window.ready = [];
    jQuery(function() {
        for( var fn, i = -1;  fn = ready[++i]; )
          fn( jQuery );
    });

Now in all fairness, the ready code has been improved in jQuery 1.3 to
remove one of these two wrapper functions, but it still has the other. And
that code could be improved just a bit more by using a direct for loop
instead of jQuery.each() - this would allow the other wrapper function to be
eliminated.

In any case, this shows how you can reduce overhead by rolling your own code
when you need the fastest performance.

Of course, if your thousands of ready functions actually *do* much, this bit
of optimization may be lost in the noise.

> Why do I really need so much on ready?

Yes! That's what we're all wondering! Don't keep us in suspense. :-)

-Mike

Reply via email to