simple-Async iterator
Using simple-async AsyncIterator to load images sequentially
HTML
<header>
<h3>AsyncIterator example</h3>
<a href="http://aravindbaskaran.github.io/simple-async/" target="_blank">Github page</a>
<h2>Darth vader makes such a good dad</h2>
<h4>Images Courtesy <a href="http://imgur.com/gallery/bmpVg">imgur</a></h4>
</header>
<div id="main" role="main">
<div id="msg"></div>
<div id="board"></div>
</div>
CSS
body {
max-width: 500px;
margin: 20px auto;
color: #777;
}
img {
max-width: 500px;
display: block;
margin: 10px auto;
border: 1px solid #DDD;
min-height: 50px;
-webkit-transition: opacity 500ms ease;
-webkit-transition-delay: 200ms;
}
.loading {
opacity: 0;
}
.done {
opacity: 1;
}
#msg {
text-align: center;
color: #333;
font-weight: bold;
}
JavaScript
function createElem(htmlStr) {
var fragment = document.createDocumentFragment(),
temp = document.createElement('div');
temp.innerHTML = htmlStr;
while (temp.firstChild) {
fragment.appendChild(temp.firstChild);
}
return fragment;
}
function onLoad() {
// array of images
var images = ["http://jsfiddle.net/img/logo.png",
"http://jsfiddle.net/img/logo.png",
"http://jsfiddle.net/img/logo.png", "http://jsfiddle.net/img/logo.png",
"http://jsfiddle.net/img/logo.png", "http://jsfiddle.net/img/logo.png",
"http://jsfiddle.net/img/logo.png", "http://jsfiddle.net/img/logo.png",
"http://jsfiddle.net/img/logo.png", "http://jsfiddle.net/img/logo.png"];
var msgEl = document.getElementById("msg");
var boardEl = document.getElementById("board");
var imgTemplate = "<img class='loading'/>";
var imageObj;
function start(itr) {
console.log("Starting...");
console.time("Total load time");
msgEl.innerHTML = "Transforming...";
imageObj = new Image();
}
function end(itr) {
msgEl.innerHTML = "The transformation is complete!";
console.log("Ending");
console.timeEnd("Total load time");
// destroy image loading object
delete imageObj;
}
// magic stepper function
function step(itr) {
// Get current item in array
var current = itr.current();
console.log("Loading - " + current);
console.time("Load time " + itr.currentIndex);
var imgFrag = createElem(imgTemplate);
var imgElem = imgFrag.children[0];
boardEl.appendChild(imgFrag);
// load image
imageObj.onload = function () {
console.timeEnd("Load time " + itr.currentIndex);
console.log("Finished loading - " + current + ", Remaining - " + itr.remaining());
imgElem.src = current;
imgElem.className = "done";
msgEl.innerHTML =...