Calling function after .load (Jquery)

To run some code after a .load() finishes, you will need to put the code in a completion function for the .load(). The load operation is asynchronous so the load function starts the loading of the content and then immediately returns and your JS execution continues (before the load has completed). So, if you’re trying to operate on the newly loaded content, it won’t be there yet.

As your code is written now, you have two blocks of code that both run when the original HTML document is ready. The first block starts a .load() operation. The second operation expects the .load() to be done already, but it has not yet completed so the content from the .load() operation is not yet available.

That’s why .load() takes a completion function as an argument. That’s a function that will be called when the load has completed. See the relevant jQuery .load() doc for more info. Here’s what your code would look like with a completion function.

$(function(){
    $('a.pageFetcher').click(function(){
        $('#main').load($(this).attr('rel'), function() {
            // put the code here that you want to run when the .load() 
            // has completed and the content is available
            // Or, you can call a function from here
        });
        // the .load() operation has not completed here yet
        // it has just been started
    });
});

Leave a Comment