I need to include several HTML files inside my main index.html
file and execute some code when the included HTML elements are finished loading. I am using the following code to load the HTML files:
function includeHTML() {
var z, i, elmnt, file, xhttp;
/* Loop through a collection of all HTML elements: */
z = document.getElementsByTagName("*");
for (i = 0; i < z.length; i++) {
elmnt = z[i];
/*search for elements with a certain atrribute:*/
file = elmnt.getAttribute("include-html");
if (file) {
/* Make an HTTP request using the attribute value as the file name: */
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4) {
if (this.status == 200) {
elmnt.innerHTML = this.responseText;
}
if (this.status == 404) {
elmnt.innerHTML = "Page not found.";
}
/* Remove the attribute, and call this function once more: */
elmnt.removeAttribute("include-html");
includeHTML();
}
};
xhttp.open("GET", file, true);
xhttp.send();
/* Exit the function: */
console.log("FILENAME: " + file);
console.log("Finished html loader IF FILE");
return;
}
}
}
As this function is loading my files recursive I can't use window.onload
or respective jquery
to trigger after my DOM is finished loading. The supposed behavior should be this way (The script is at the bottom of the body tag):
<script type="text/javascript">
includeHTML();
window.onload = function () {
console.log("DOM loaded");
// Do stuff after includeHTML is done and all DOM Elements can be retrieved with
// document.getElementById();
};
</script>
Right now if I am running js code to be executed the XHTML Requests are still not finished loading all my DOM Content but the js code is executed anyway, I need to make sure that all HTML Content is available before continuing my work.