Load external JavaScript with ES6 promises
Sometimes you just need to load a script on the fly. Whether you are dropping down into a console or embedding your script in a place where you have no guarantee what libraries will be available, it can be an inescapable requirement. Since the import
syntax is not part of the ES6 specification, scripts are still have to the use the tried and true method of embedding a script tag and waiting for it to load in a callback.
However, ES6 provides a way to handle callbacks in a more streamlined and elegant way: Promises. Here is a simple object that will handle it for you. It provides two interfaces to load scripts. The importer.url
method allows you to load a single script and returns a promise when it is done loading. The importer.urls
method takes an array of script URLs and returns a single promise when all of them have finshed loading.
const importer = {
url: (url) => {
return new Promise((resolve, reject) => {
let script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
script.addEventListener('load', () => resolve(script), false);
script.addEventListener('error', () => reject(script), false);
document.body.appendChild(script);
});
},
urls: (urls) => {
return Promise.all(urls.map(importer.url));
}
};