franbenz
franbenz

Reputation: 712

jQuery runtime ready event after loading another page

var x = $("<div ></div>");
$('body').append(x);
x.load('page.html'
    , function() {
        $(document).ready(
            function (){
            //useful stuff here;
            }
        );  
    });

I'm expecting the ready callback function to be executed after the page.html is fully loaded and already executed all it's scripts inside my "div".
This example works.
My question is: Is this the right way to do what I'm expecting? Is there any other way? What's the logic behind the ready event in this case? Should it be applied on "document", "this" or "x"?

Upvotes: 1

Views: 849

Answers (2)

jrey
jrey

Reputation: 2183

dummy.html

<SCRIPT>
    $(document).ready(
        function(){
            var x = $("<div >hola</div>");
            $('body').append(x);
            x.load('dummy2.html', function() {

                console.log('dummy callback');

                $(document).ready(
                    function (){
                    console.log('dummy has loaded after dummy2 has loaded');
                    //useful stuff here;
                    }
                );
            });
        }
    );
</SCRIPT>

dummy2.html

 <SCRIPT>
    $(document).ready(
        function(){
            console.log('dummy 2a has load');
        }
    );
    $(document).ready(
        function(){
            console.log('dummy 2b has load');
        }
    );


</SCRIPT>

This example shows how to works the sequence, first print dummy callback', second: dummy 2a and dummy 2b, and the last print is 'dumy has loaded after dummy has loaded', i do know why works ok, but the sequence works OK.

Update

if you remove the line $(document).ready the sequence is

first: dummy callback second: dummy has loaded... /Wrong!/

Upvotes: 1

Sushanth --
Sushanth --

Reputation: 55740

You load event should be encased in DOM ready ..

$(document).ready(function () {
    var x = $("<div ></div>");
    $('body').append(x);
    x.load('page.html', function () {

        //useful stuff here;
    });
});

No need for the callback to be enclosed in DOM ready handler..

It works in this case as you do not seem to select any already existing element on the page. So it will work fine event without the DOM ready handler

Upvotes: 2

Related Questions