Skip to content

Instantly share code, notes, and snippets.

@rapzo
Forked from pamelafox/jquery.delayload.js
Created March 26, 2014 13:18
Show Gist options
  • Save rapzo/9782948 to your computer and use it in GitHub Desktop.
Save rapzo/9782948 to your computer and use it in GitHub Desktop.
// Functions to help figure out whether elements are in the viewport
// and lazy-load their content if so.
// Implemented as jQuery plugins.
(function() {
$.fn.inView = function(nearThreshold) {
var $elem = $(this);
// Checks if its visible, CSS-wise
if (!$elem.is(":visible")) {
return false;
}
// Checks if its visible, screen-wise, within threshold
var viewportHeight = $(window).height();
var scrollTop = window.pageYOffset || document.documentElement.scrollTop;
var elemTop = $elem.offset().top;
nearThreshold = nearThreshold || 0;
if ((scrollTop + viewportHeight + nearThreshold) > elemTop) {
return true;
}
return false;
};
$.fn.delayLoad = function(nearThreshold) {
var $elem = $(this);
// divs with background-image set
if ($elem.data("delayed-bgimage") &&
$elem.css("background-image") === "none" &&
$elem.inView(nearThreshold)) {
_.defer(function() {
$elem.css("background-image", "url(" + $elem.data("delayed-bgimage") + ")");
});
return true;
}
// iframes or images
if ($elem.data("delayed-src") &&
(!$elem.attr("src") || $elem.attr("src") === "about:blank") &&
$elem.inView(nearThreshold)) {
_.defer(function() {
$elem.attr("src", $elem.data("delayed-src"));
});
return true;
}
return false;
};
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment