preload images before showing images
by Darby Rathbone
HTML
something already <there></there>
CSS
preload {
display: none;
}
JavaScript
imgArr = [];
imgs = [
'http://i.imgur.com/m2RyXco.jpg',
'http://i.imgur.com/m2RyXco.jpg',
'http://i.imgur.com/m2RyXco.jpg',
'http://i.imgur.com/m2RyXco.jpg',
'http://i.imgur.com/m2RyXco.jpg',
'http://i.imgur.com/m2RyXco.jpg',
'http://i.imgur.com/m2RyXco.jpg',
'http://i.imgur.com/m2RyXco.jpg',
'http://i.imgur.com/m2RyXco.jpg'];
for (i = 0; i < imgs.length; i++) {
var imageObj = new Image();
imageObj._complete = false;
imageObj.onload = function () {
this._complete = true;
};
imageObj.src = imgs[i];
imgArr.push(imageObj);
}
if (imgArr.length >= imgs.length) {
// console.log(imgArr);
var event = new CustomEvent('imagesloaded', {
'images': null
});
setTimeout(function wait() {
if (imgArr.every(function (_e) {
return _e.complete;
})) {
event.images = [].slice.call(imgArr);
window.dispatchEvent(event);
} else setTimeout(wait, 100);
}, 100);
}
window.addEventListener('imagesloaded', function (e) {
e.images.forEach(function (_e) {
document.body.appendChild(_e)
});
});