Loading script dynamically. Keep in mind some time we will have libs that are dependent on some other library.
By default browser loads them synchronously. To do the same thing
Follow logic will help you.
const loadScript = (document, script) => {
return new Promise((resolve, reject) => {
const newScript = document.createElement('script');
newScript.onload = resolve;
newScript.onerror = reject;
newScript.async = true;
newScript.appendChild(document.createTextNode(script.innerHTML));
Array.from(script.attributes).forEach(attr => newScript.setAttribute(attr.name, attr.value));
script.parentNode.appendChild(newScript);
})
}
for (let index = 0; index < scripts.length; index++) {
try {
const script = scripts[index];
// Loading the scripts synchronously to resolve the prior dependencies
await loadScript(doc, script);
} catch (error) {
console.log('Failed at loading scripts: ', error)
}
}