JSFiddle - React, Tailwind, and code Playground

by Dimitar Christoff

HTML

<script src="https://rawgithub.com/DimitarChristoff/pre-loader/master/pre-loader.js"></script>
<div id="images"></div>
<!-- look at external resources where the pre-loader.js is added -->

CSS

#images {
    display: none;
}
span {
    font-family: arial;
    font-size: 12px;
    padding-left: 8px;
}

JavaScript

// assign 50 non-cache-able images via an image generator
var imagesArray = new Array(50).join(',').split(',');
imagesArray = imagesArray.map(function(el, i){
    return 'http://dummyimage.com/600x400/000/' + (255 - i) + '?' + +new Date();
});

// create a HTML5 progress element
var progress = document.createElement('progress');
progress.setAttribute('max', imagesArray.length);
progress.setAttribute('value', 0);
document.body.appendChild(progress);

var legend = document.createElement('span');
document.body.appendChild(legend);
var imageContainer = document.getElementById('images');

// instantiate the pre-loader with an onProgress and onComplete handler
new preLoader(imagesArray, {
    onProgress: function(img, imageEl, index){
        // fires every time an image is done or errors. 
        // imageEl will be falsy if error
        console.log('just ' +  (!imageEl ? 'failed: ' : 'loaded: ') + img);
        
        var percent = Math.floor((100 / this.queue.length) * this.completed.length);
        
        // update the progress element
        legend.innerHTML = '<span>' + index + ' / ' + this.queue.length + ' ('+percent+'%)</span>';
        progress.value = index;
        
        imageContainer.appendChild(imageEl);
        // can access any propery of this
        console.log(this.completed.length + this.errors.length + ' / ' + this.queue.length + ' done');
    }, 
    onComplete: function(loaded, errors){
        // fires when whole list is done. cache is primed.
        console.log('done', loaded);
        imageContainer.style.display = 'block';
        
        if (errors){
            console.log('the following failed', errors);
        }
    }
});