Ah, finally you ask the *real* question.

Let's start with that next time, OK? ;-)

Don't feel bad, it's a good thing to provide a simplified test case - but in
this case the simplified example obscured the essential problem. The problem
isn't the order of execution of <script> tags, or whether document.ready
code in a later script tag could somehow get run before an earlier script
tag is executed (an impossibility since script tags are executed in order).

The real problem:

You are loading a third-party script. That script adds an element to the
DOM, and you want to access that element after it's created.

You don't know how or when that script decides to add this element. It could
use any number of techniques, including a setTimeout() to delay creation a
bit (a common trick). Or maybe it uses the window.onload event.

Either of those could happen after all script tags are loaded, and after
jQuery's document.ready. So you need some other way of waiting for your
element to be created.

Here's one way you could do that. Beware, it's untested, but it's pretty
simple and similar to code I've used in the past:

    // Repeatedly check $(selector).length, and when it is >= count,
    // call the callback function, with "this" set to a new jQuery
    // object for the same selector.

    jQuery.elementsReady = function( selector, count, callback ) {
        
        var timer;
        if( ! ready() ) timer = setInterval( ready, 50 );
        
        function ready() {
            if( jQuery(selector).length < count ) return false;
            if( timer ) clearInterval( timer );
            callback.apply( jQuery(selector) );
            return true;
        }
    };

Now you can wait for your element like this:

    $.elementsReady( '#cometchatbase', 1, function() {
        // append something to the cometchatbase element
        this.append( '<div>howdy!</div>' );
    });

Let me know if that does the trick. Note that it uses a 50 millisecond
interval timer - you can adjust that any way you want, of course.

Also you can check for multiple elements in one $.elementsReady() call -
just use an appropriate selector and count value.

-Mike

> From: Veeru
> 
> I have an example for the scenario
> I am using cometchat in my application.
> Its a third party script, that provides a chat interface to 
> the website. It adds some containers to the body of the 
> document. One such container is cometchatbase.
> 
> I want attach something to this container on document.ready. 
> But by the time document.ready is fired, the container is not 
> generated, so $j
> ("#cometchatbase") returns null. Does this mean, before the 
> cometchat.js has finished executing document.ready has already fired?
> 
> Thanks
> Vru
> 

Reply via email to