I have a website which has two files; main.js
and loading.js
loading.js
waits for DOMContentLoaded
, then clears a loading screen cover.
main.js
also waits for DOMContentLoaded
, but also waits for loading.js
to finish its DOMContentLoaded
, then executes some more code.
I need to write some code (possibly using Promise
s?) which allows this to happen.
Here is my code:
loading.js
document.addEventListener('DOMContentLoaded', () => {
var loadingCover = document.querySelector('#loading-cover');
loadingCover.style.display = 'none';
});
main.js
document.addEventListener('DOMContentLoaded', () => {
/* Wait for loading.js */
console.log("Do stuff");
});
I've done some research with Promise
s, but I can't wrap my head around how they could work in this situation.
I've tried using a Promise
which is resolved inside loading.js
. main.js
then waits for that Promise
to be resolved before executing its own code.
Ideally, this would be the code:
loading.js
const loadingPromise = new Promise();
document.addEventListener('DOMContentLoaded', () => {
var loadingCover = document.querySelector('#loading-cover');
loadingCover.style.display = 'none';
loadingPromise.resolve();
});
main.js
/* Terrible example */
loadingPromise.addEventListener('resolve', () => {
console.log("Do stuff");
});