I'm working on a SPA (Single Page Application) project and need to load files in a dynamic and controlled way (CSS, HTML and JS)
I created the structure below (in this example only for CSS), but although the files are injected into the page, the promise is never resolved
A peculiarity of the structure is that the "resolve" and "reject" of each "promise" created are saved to be executed outside the original "promise" function
This is necessary because if the "promise" is successful, the control events must be removed, and if an error occurs, the element must be removed
'use strict';
const
css=
(
()=>
{
const
load=
url=>
{
return new Promise(
(resolve,reject)=>
{
let
link=document.createElement("link");
link.setAttribute("href",url);
link.setAttribute("rel","stylesheet");
link.addEventListener("load",onSuccess);
link.addEventListener("error",onError);
resolveAhead=resolve;
rejectAhead=reject;
document.head.appendChild(link);
}
);
},
onSuccess=
event=>
{
event.target.removeEventListener("load",onSuccess);
event.target.removeEventListener("error",onError);
resolveAhead(event);
},
onError=
event=>
{
document.head.removeChild(event.target);
rejectAhead(event);
};
let
resolveAhead,
rejectAhead;
return {
load
}
}
)();
Promise.all(
[
css.load("style1.css"),
css.load("style2.css"),
css.load("style3.css"),
css.load("style4.css"),
css.load("style5.css"),
css.load("style6.css")
]
).then(
response=>
{
console.log(response);
alert("Well done");
}
).catch(
response=>
{
console.log(response);
alert("Houston... we've had a problem here");
}
);