kitimenpolku
kitimenpolku

Reputation: 2604

document.ready() inside a function after and Ajax call

I have an application that is using ajax calls for loading the content. Those ajax calls are retrieving just the HTML. JavaScript is in another file.

After doing the AJAX-call I will call to a function that should start executing the JavaScript as soon as possible.

Here I leave a small function that will retrieve some code from an ajax call:

function loadPage(page) {
    $(".container").html("");
    if(page == "page1") {
        $.ajax({
            url: "/page1.php",
            success: function(html){
                $(".container").html(html);
                loadPage1Script();
            } 
        });
    }else if(page == "page2"){
        $.ajax({
            url: "/page2.php",
            success: function(html){
                $(".container").html(html);
                loadPage2Script();
            } 
        });
    }
}

After that, they will execute loadPage1Script() or loadPage2Script().

function loadPage1Script(){
    //Start the carousel plugin, for example
}

A new code has been added to the HTML structure. Should I call to $(document).ready(); in the loadPage1Script() before executing the code to to attach all event handlers? Is there any differences if I do not do that? Will the script start faster if I add the $(document).ready(); ?

function loadPage1Script(){
    $(document).ready(function(){
        //Start the carousel plugin, for example
    });
}

Taken from jQuery site(http://api.jquery.com/ready/):

"In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed. The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers and run other jQuery code."

Upvotes: 0

Views: 2169

Answers (2)

Anthony Grist
Anthony Grist

Reputation: 38345

There's no need to use $(document).ready() inside of those functions, because by the point they're run the DOM elements they need will already be present (you just inserted them into the page prior to calling the function).

You should, however, call the original loadPage function inside of $(document).ready() to ensure that the .container element(s) exist.

Upvotes: 1

whitneyit
whitneyit

Reputation: 1226

If you are calling the loadpage function after you have aleady called

$( document ).ready( function () {
    ...
});

Then it shouldn't matter. Also, since the $.fn.html function isn't asynchronous, you will have no problem in running your loadPageScript functions straight away

Upvotes: 1

Related Questions