JSFiddle - React, Tailwind, and code Playground
JavaScript
function imagePreloader(list, onload, each, onerror)
{
this.list = list || null;
this.onload = onload || null;
this.each = each || null;
this.onerror = onerror || null;
this.ready =
this.ignoreErrors =
this.aborted = false;
this.loaded = 0;
this.quantity = null;
};
imagePreloader.prototype.load = function()
{
var self = this;
this.quantity = 0;
this.ready = false;
//for(var i in this.list) this.quantity++;
for(var i in this.list)
{
if(typeof this.list[i] != "string") continue;
this.quantity++;
var uri = this.list[i];
this.list[i] = new Image();
this.list[i].nome = i;
this.list[i].addEventListener("load", function()
{
self.loaded++;
if(self.aborted) return;
var nome = this.nome;
delete this.nome;
if(self.loaded == self.quantity)
{
self.ready = true;
typeof self.each == "function" && self.each(this, nome);
typeof self.onload == "function" && self.onload();
}
else typeof self.each == "function" && self.each(this, nome);
}, false);
this.list[i].addEventListener("error", function()
{
if(self.ignoreErrors) this.dispatchEvent(new Event("load"));
else
{
typeof self.onerror == "function" && self.onerror(this);
self.aborted = true;
}
}, false);
this.list[i].src = uri;
}
return this;
};
var loader = new imagePreloader(
{
googleLogo: "https://www.google.com/logos/2012/startrek2012-sr.png",
JSFiddleLogo: "http://jsfiddle.net/img/logo.png"
});
loader.onload = function()
{
document.body.appendChild(this.list.googleLogo);
document.body.appendChild(this.list.JSFiddleLogo);
};
loader.load();