Skip to content

Instantly share code, notes, and snippets.

@Rycochet
Last active August 29, 2015 14:15
Show Gist options
  • Save Rycochet/dbe6b581f6b9aab787c7 to your computer and use it in GitHub Desktop.
Save Rycochet/dbe6b581f6b9aab787c7 to your computer and use it in GitHub Desktop.
Sinple jQuery lazy-loading
/**
* Shortcut to getBoundingClientRect
* @param {Element} element
*/
function getRect(element) {
if (element === window) {
return {
top: 0,
right: element.innerWidth,
bottom: element.innerHeight,
left: 0,
height: element.innerHeight,
width: element.innerWidth
};
}
var rect = element.getBoundingClientRect();
return {
top: rect.top,
right: rect.right,
bottom: rect.bottom,
left: rect.left,
height: rect.height || (rect.bottom - rect.top),
width: rect.width || (rect.right - rect.left)
};
}
/**
* Check if an element is even partially visible within a container
* @param {(Element|DOMRect)} container
* @param {(Element|DOMRect)} element
* @param {Number} threshold
* @return {Boolean}
*/
function isInside(container, element, threshold) {
if (element && element.nodeType) {
element = getRect(element);
}
if (!element || (!element.top && !element.left && !element.bottom && !element.right)) {
// The element (or one of it's parents) is display: none
return false;
}
if (container && container.nodeType) {
container = getRect(container);
}
if (!container || (!container.top && !container.left && !container.bottom && !container.right)) {
// The container (or one of it's parents) is display: none
return false;
}
threshold = threshold || 0;
var containerTop = container.top - threshold,
containerBottom = container.bottom + threshold,
containerLeft = container.left - threshold,
containerRight = container.right + threshold;
return ((element.top >= containerTop && element.top <= containerBottom)
|| (element.bottom >= containerTop && element.bottom <= containerBottom)
|| (element.top < containerTop && element.bottom > containerBottom))
&& (
(element.left >= containerLeft && element.left <= containerRight)
|| (element.right >= containerLeft && element.right <= containerRight)
|| (element.left < containerLeft && element.right > containerRight));
}
/**
* Lasy load images or anything else, search for data-<data-lazyload>, and when visible simply move that over to <data-lazyload>
*/
$.fn.lazyLoad = function() {
var windowPos = getRect(window);
$(this).find("img[data-lazyload],source[data-lazyload]").each(function() {
if (isInside(this, windowPos, 200)) {
var $this = $(this),
attr = $this.attr("data-lazyload");
$this
.attr(attr, $this.attr("data-" + attr))
.removeAttr("data-lazyload")
.removeAttr("data-" + attr);
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment