Image lazy loader
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

103 lines
2.4 KiB

11 years ago
/*! Echo v1.5.0 | (c) 2014 @toddmotto | MIT license | github.com/toddmotto/echo */
window.Echo = (function (global, document, undefined) {
11 years ago
'use strict';
11 years ago
/**
* store
* @type {Array}
*/
var store = [];
11 years ago
/**
* offset, throttle, poll vars
*/
var offset, throttle, poll;
/**
* _inView
* @private
* @param {Element} element Image element
* @returns {Boolean} Is element in viewport
*/
var _inView = function (element) {
var coords = element.getBoundingClientRect();
return ((coords.top >= 0 && coords.left >= 0 && coords.top) <= (window.innerHeight || document.documentElement.clientHeight) + offset);
11 years ago
};
11 years ago
/**
* _pollImages Loop through the images if present
* or remove all event listeners
* @private
*/
11 years ago
var _pollImages = function () {
11 years ago
var length = store.length;
if (length > 0) {
for (var i = 0; i < length; i++) {
var self = store[i];
if (self && _inView(self)) {
self.src = self.getAttribute('data-echo');
store.splice(i, 1);
length = store.length;
i--;
}
}
} else {
if (document.removeEventListener) {
global.removeEventListener('scroll', _throttle);
} else {
global.detachEvent('onscroll', _throttle);
11 years ago
}
11 years ago
clearTimeout(poll);
11 years ago
}
};
11 years ago
/**
* _throttle Sensible event firing
* @private
*/
var _throttle = function () {
clearTimeout(poll);
poll = setTimeout(_pollImages, throttle);
};
11 years ago
/**
* init Module init function
* @param {Object} [obj] Passed in Object with options
* @param {Number|String} [obj.throttle]
* @param {Number|String} [obj.offset]
*/
var init = function (obj) {
11 years ago
var nodes = document.querySelectorAll('[data-echo]');
var opts = obj || {};
11 years ago
offset = parseInt(opts.offset || 0);
throttle = parseInt(opts.throttle || 250);
for (var i = 0; i < nodes.length; i++) {
store.push(nodes[i]);
}
11 years ago
_pollImages();
11 years ago
if (document.addEventListener) {
11 years ago
global.addEventListener('scroll', _throttle, false);
global.addEventListener('load', _throttle, false);
} else {
11 years ago
global.attachEvent('onscroll', _throttle);
global.attachEvent('onload', _throttle);
}
11 years ago
11 years ago
};
11 years ago
/**
* return Public methods
* @returns {Object}
*/
11 years ago
return {
init: init,
11 years ago
render: _pollImages
11 years ago
};
11 years ago
})(this, document);