HTML load one script after another script completes execution
await
doesn't block the execution of the entire script. await
s are just hiding promise(s) into a synchronous-looking construction. When await
is met in a function marked as async
, the expression following await
, often a function call, is executed, but the return value is not waited inside the async
function. Instead, the function marked with async
is paused, and the execution continues from the point the async
function was called, and the rest of the script is executed (and perhaps also other scripts), until the promise is fullfilled, Then the script execution resumes to the async
function, and continues from the next statement after the statement where await
operator originally paused the async
function.
You can use a promise like this:
In script1:
const headerHtml = new Promise((resolve, reject) => {
fetch("./header.html")
.then(response => response.text())
.then(data => {
document.getElementById("header").innerHTML = data;
resolve();
});
});
In script2:
headerHtml.then(() => {
// Now header.html is fully loaded
// Do what you need to do with the new elements
});
This will work even when fetch
would had been completely resolved before then
handler is set in script2 (or anywhere in general), because "If the promise has already been fullfilled or rejected when a corresponding handler is attached, the handler will be called"MDN.