I am now having a whole html string and need to create the page from it and await it to load before continuing next.
I first tried:
let writeHTMLAndLoad = function() {
return new Promise((resolve) => {
document.open();
window.addEventListener("load",resolve());
document.write(strHTML);
document.close();
});
}
await writeHTMLAndLoad();
//Code continue after...
But the script just directly continued. The html is seens written. But the page, mainly images and some html elements, just not loaded at all
I tried to put resolve without parenthesis, the script changed to await forever.
The same scenario, await forever, apply to cases of seaparting resolve (with or without parenthesis) into a dummy function
let writeHTMLAndLoad = function() {
return new Promise((resolve) => {
function dummy() {
resolve();
}
document.open();
window.addEventListener("load",dummy);
document.write(strHTML);
document.close();
});
}
await writeHTMLAndLoad();
//Code continue after...
But I found the load event can be successully triggered, if I deliberately force the script to continue by resolving directly after document.close();
let writeHTMLAndLoad = function() {
return new Promise((resolve) => {
function dummy() {
console.log("Loaded")
}
document.open();
window.addEventListener("load",dummy());
document.write(strHTML);
document.close();
resolve();
});
}
await writeHTMLAndLoad();
//Code continue after...
In this case, the console.log("Loaded")
printed out in the middle of the scirpt continued after.
May I know how I can resolve successully of the window load event?
I have to use the window load event as the indicator, as I have to use the images loaded.
I currently separated the code that intended to process after the load event into another function and asked the dummy function to call it. But in this case my script just separated into two large parts and prefer not to use this approach. So I would be really appreciated if the load event can be resolved correctly and so the code can be looked logically continue.