Skip to content

Instantly share code, notes, and snippets.

@coderofsalvation
Last active April 3, 2019 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coderofsalvation/f16a6902af5c66ec99c121568a43b447 to your computer and use it in GitHub Desktop.
Save coderofsalvation/f16a6902af5c66ec99c121568a43b447 to your computer and use it in GitHub Desktop.
load() - a deadsimple javascript function to load js/css in a controlled fashion
/*
* more controlled way of loading javascript & css in index.html
*
* purposes:
* - quicker/smoother rendering of 1st meaningful frame and css preloading animations
* - save performance by adding delays to tracker-jscode (analytics etc)
* - conditional logic (only load certain js/css files based on url-flags, server port etc)
*
* example:
*
* load([
* {src:"/js/stylus.min.js"},
* {src:"https://cdn.polyfill.io/v2/polyfill.js?features=es6,fetch,Promise"},
* ],
* load([
* {src:"/js/main.js"},
* {src:"https://google.com/analytics/k2j3kj423", load: (i) => setTimeout(i,2000) }
* ])
* )()
*
* require('/foo.js').then( () => alert("nice!") ) // manual way of loading js-file
*/
function load(files, cb) {
window.require = function(url, type) {
return new Promise(function(resolve, reject) {
type = type == 'js' ? 'js' : 'css'
var tag = document.createElement(type == 'js' ? 'script' : 'link');
if (type == 'css')
tag.rel = "stylesheet"
tag[type == 'js' ? 'src' : 'href'] = url;
tag.addEventListener('load', function() {
resolve(tag);
}, false);
tag.addEventListener('error', function() {
reject(tag);
console.log('require(' + url + ') failed')
}, false);
document.body.appendChild(tag);
}
)
}
return function(files,cb){
// load other scripts after first meaningful frame
setTimeout(function() {
Promise.all(files.map((f)=>{
!f.load ? require(f.src, "js") : new Promise(function(src, delay, resolve, reject) {
f.load( function(){ require(f.src, "js") } )
}
.bind(this, f.src, f.delay))
}
)).then(()=>cb ? cb() : false)
}, 1000)
}.bind(this,files,cb)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment