简体   繁体   中英

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?

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);

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);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM