I’d use Promises for state-management and Promise.all to check when all scripts are loaded.
function load(src) {
return new Promise((resolve, reject) => {
const script = document.createElement('script');
script.onload = resolve;
script.onerror = reject;
script.async = true;
script.src = src;
document.head.appendChild(script);
});
}
Promise.all(scripts.map(load)).then(callback);
In my app.js I do something like this:
load(src) {
script = document.createElement('script');
script.src = src;
script.async = true;
document.head.appendChild(script);
}
for (var i=0; scripts.length; i++) {
load(scripts[i])
}
callback();
all the scripts are fetched with async flag. I want to execute callback
only when all the scripts are loaded, how can I do it?
This is basically the same approach as I would typing up. This is a solid and clean approach.