Skip to content

Instantly share code, notes, and snippets.

@raybogman
Forked from pamelafox/jquery.delayload.js
Last active August 29, 2015 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save raybogman/c70b4940b048c92dcea0 to your computer and use it in GitHub Desktop.
Save raybogman/c70b4940b048c92dcea0 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