Skip to content

Instantly share code, notes, and snippets.

@Ulv
Created November 1, 2013 10:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ulv/7263845 to your computer and use it in GitHub Desktop.
Save Ulv/7263845 to your computer and use it in GitHub Desktop.
lazy load images. No jQuery or such req.
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