Skip to content

Instantly share code, notes, and snippets.

@moust
Last active August 29, 2015 14:23
Show Gist options
  • Save moust/9229f18caeb057c58287 to your computer and use it in GitHub Desktop.
Save moust/9229f18caeb057c58287 to your computer and use it in GitHub Desktop.
JavaScript Preloader
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Preload</title>
</head>
<body>
<progress id="loading" value="0"></progress>
<script src="preload.js"></script>
<script>
var images = [
"http://placehold.it/100x100&text=1",
"http://placehold.it/100x100&text=2",
"http://placehold.it/100x100&text=3",
"http://placehold.it/100x100&text=4",
"http://placehold.it/100x100&text=5"
];
var loading = document.querySelector("#loading");
document.addEventListener("image_loaded", function (event) {
loading.value = event.detail.loaded;
loading.max = event.detail.total;
});
var loader = new Preload(images)
.then(
function (images) {
images.forEach(function (image) {
document.body.appendChild(image);
});
},
function () {
var message = document.createElement('p');
message.style.color = "red";
message.innerText = "Erreur lors du chargement des images.";
document.body.appendChild(message);
}
);
</script>
</body>
</html>
var Preload = function (images) {
if (!Array.isArray(images)) {
images = [images];
}
this.images = images;
this.loaded = 0;
var loaders = this.images.map(this.createLoader.bind(this));
return Promise.all(loaders);
};
Preload.prototype.createLoader = function (src) {
var loader = new Promise(
function (resolve, reject) {
var img = new Image();
img.onload = function () {
resolve(img);
};
img.onerror = function () {
reject(Error("Image loading error."));
};
img.onabort = function () {
reject(Error("Abort loading image."));
};
img.src = src;
}
);
loader.then(
function () {
this.loaded++;
}.bind(this),
function () {}
);
loader.then(
function () {
document.dispatchEvent(
new CustomEvent("image_loaded", {
"detail": {
"loaded": this.loaded,
"total": this.images.length
}
})
);
}.bind(this),
function () {}
);
return loader;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment