Raghav
Raghav

Reputation: 53

Why does my JavaScript function run before my jQuery load() call finishes loading?

I have a JavaScript file along with HomePage.xhtml, and Header.xhtml.

Header.xhtml is included in HomePage.xhtml, using JavaScript.

Here is the sample code of my JavaScript file:

$(document).ready(function() {

    loadTemplate();
    loadUserContext();
});

function loadTemplate() {

    $(function() {
       $("#rcHeaderblock").load("Header.xhtml");
    });
}

function loadUserContext(){

    var sessionValue = 'Welcome, Guest';
    $('#networkID p:nth-child(1)').text(sessionValue);
}

The networkID is the id of a div tag present in Header.xhtml to be replaced dynamically.

But by doing a couple of debug steps I found out that loadUserContext is being called before the Header.xhtml is actually loaded in to my HomePage.xhtml.

Why?

Upvotes: 1

Views: 113

Answers (2)

Vishwanath
Vishwanath

Reputation: 6004

jQuery’s load function uses ajax (which is asynchronous) to load the HTML file.

Asynchronous operations don’t halt the flow of execution and the code continues to execute in a serial fashion. After the asynchronous operation has completed, the callback for the operation is called. You can register the callback for the asynchronous operations.

In your case you can use the callback provided by load to perform the operation on the HTML loaded:

$("#rcHeaderblock").load( "Header.xhtml", function() {
    var sessionValue = 'Welcome, Guest';
    $('#networkID p:nth-child(1)').text(sessionValue);
});

Upvotes: 2

blgt
blgt

Reputation: 8205

load is asynchronous. However, it provides a callback mechanism for exactly the situation you described. What you probably want to do is along the lines of:

$("#rcHeaderblock").load("Header.xhtml", loadUserContext);

and then just

$(document).ready(loadTemplate);

Upvotes: 4

Related Questions