Created
January 30, 2014 09:09
-
-
Save pamelafox/8705015 to your computer and use it in GitHub Desktop.
Delay Loading
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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