I know this question may sound repetitive, but I've been searching for a solution for a long time, and couldn't find any.
I have a method that resolves a promise after the window is loaded. Later, I am waiting for that method in my mounted hook. When routing to that page, neither the promise itself, nor anything after it is executed. However, if I refresh the page, everything runs smoothly.
As an example, this is my method:
getPosition() {
return new Promise((resolve, reject) => {
window.addEventListener("load", () => {
console.log("window is loaded");
resolve();
});
});
},
This is my mounted hook:
async mounted() {
console.log("before promise"); // this logs
await this.getPosition(); // this does not log
console.log("after promise"); // this does not log
},
getPosition is not guaranteed to be executed before load, and race condition will result in pending promise. That a window has already been loaded should be additionally checked:
new Promise(resolve => {
if (document.readyState === 'complete') {
resolve();
return;
}
window.addEventListener("load", () => resolve());
});
load event happens after loading all images and styles, which is not usually needed but results in additional delay. Most times it's useful to wait for DOM instead:
new Promise(resolve => {
if (document.readyState !== 'loading') {
resolve();
return;
}
document.addEventListener("DOMContentLoaded", () => resolve());
});
load and DOMContentLoaded event are expected to be emitted once on initial page load. Subsequent DOM changes and network requests aren't supposed to be tracked through them.