Created
November 1, 2013 10:55
-
-
Save Ulv/7263845 to your computer and use it in GitHub Desktop.
lazy load images. No jQuery or such req.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
window.echo = (function (window, document) { | |
'use strict'; | |
var Echo = function (elem) { | |
this.elem = elem; | |
this.render(); | |
this.listen(); | |
}; | |
var echoStore = []; | |
var scrolledIntoView = function (element) { | |
var coords = element.getBoundingClientRect(); | |
return ((coords.top >= 0 && coords.left >= 0 && coords.top) <= (window.innerHeight || document.documentElement.clientHeight)); | |
}; | |
var echoSrc = function (img, callback) { | |
img.src = img.getAttribute('data-echo'); | |
if (callback) { | |
callback(); | |
} | |
}; | |
var removeEcho = function (element, index) { | |
if (echoStore.indexOf(element) !== -1) { | |
echoStore.splice(index, 1); | |
} | |
}; | |
var echoImages = function () { | |
for (var i = 0; i < echoStore.length; i++) { | |
var self = echoStore[i]; | |
if (scrolledIntoView(self)) { | |
echoSrc(self, removeEcho(self, i)); | |
} | |
} | |
}; | |
Echo.prototype = { | |
init: function () { | |
echoStore.push(this.elem); | |
}, | |
render: function () { | |
if (document.addEventListener) { | |
document.addEventListener('DOMContentLoaded', echoImages, false); | |
} else { | |
window.onload = echoImages; | |
} | |
}, | |
listen: function () { | |
window.onscroll = echoImages; | |
} | |
}; | |
var lazyImgs = document.querySelectorAll('img[data-echo]'); | |
for (var i = 0; i < lazyImgs.length; i++) { | |
new Echo(lazyImgs[i]).init(); | |
} | |
})(window, document); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment