Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Lazy load JS and CSS assets
var ASSET_TYPE = {
css: 'css',
js: 'js'
};
function loadCss(source) {
return new Promise(function(resolve, reject) {
var link = document.createElement('link');
link.type = "text/css";
link.rel = "stylesheet";
link.onload = function () { resolve() };
link.href = source.url;
document.head.appendChild(link);
});
}
function loadSciptTag(source) {
return new Promise(function(resolve, reject) {
var script = document.createElement('script');
script.src = source.url;
script.async = source.async || 0;
script.onload = function () { resolve() };
document.body.appendChild(script);
});
}
function lazyLoader(asset) {
switch (asset.type) {
case ASSET_TYPE.css:
return loadCss(asset.source)
break;
case ASSET_TYPE.js:
return loadSciptTag(asset.source)
break;
default:
return Promise.resolve();
break;
}
}
function loadAssets(assets) {
const dependencies = Array.isArray(assets) ? assets : [assets];
return dependencies.map(lazyLoader);
}
// USAGE
const assetLoadPromises = loadAssets(
[{
type: ASSET_TYPE.js,
source: {
url: 'https://code.jquery.com/jquery-3.2.1.slim.min.js',
async: 1
}
},
{
type: ASSET_TYPE.css,
source: {
url: 'https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css'
}
}]
);
// wait for all the dependencies to load
Promise.all(assetLoadPromises)
.then(function() {
console.log('All assets are loaded');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment