Created
September 20, 2016 10:23
-
-
Save Andrinoid/92cc4f84493baf4e7966d1ec2491ebde to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//There are a lot of image preloaders out there | |
// This one is supposed to be forgiving | |
// depends on Emmitter https://github.com/JFusco/es6-event-emitter | |
class Preloader extends Emitter { | |
constructor(pathList, options) { | |
super(); | |
this.defaults = { | |
prefix: null | |
}; | |
_.extend(this.defaults, options); | |
this.pathList = pathList; | |
this.loadedImages = []; | |
this.total = this.pathList.length; | |
this.counter = 0; | |
this.percent = 0; | |
this.loadImages(); | |
} | |
//overides | |
// each(count, percent) {} | |
// done(imageList) {} | |
loadImages() { | |
let self = this; | |
for (var i = 0; i < this.pathList.length; i++) { | |
try { | |
var img = this.loadedImages[i] = document.createElement('img'); | |
if (this.defaults.prefix) { | |
//add trailing slash if doesn't exists | |
var prefix = this.defaults.prefix.replace(/\/?$/, '/'); | |
} | |
else { | |
prefix = ''; | |
} | |
img.onload = ()=> { | |
this.counter++; | |
this.percent = (this.counter / this.total) * 100; | |
this.trigger('each', this.counter, this.percent); | |
if (this.counter === this.total) { | |
this.trigger('done', this.loadedImages); | |
} | |
}; | |
img.onerror = (err)=> { | |
//prevent component from stoping if last image is not found | |
this.counter++; | |
if (this.total === this.counter) { | |
this.trigger('each', this.counter, 100); | |
this.trigger('done', this.loadedImages); | |
} | |
}; | |
img.src = prefix + this.pathList[i]; | |
} catch (err) { | |
console.warn(err); | |
} | |
} | |
} | |
} | |
// example usage | |
let preloader = new Preloader(list, { | |
prefix: 'static/images' | |
}); | |
preloader.on('each', (count, percent) => { | |
console.log(count, percent); | |
}); | |
preloader.on('done', (rsp) => { | |
console.log(rsp); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment