Reputation: 53
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
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