Skip to content

Instantly share code, notes, and snippets.

@prosenjit-manna
Created October 28, 2015 04:54
Show Gist options
  • Save prosenjit-manna/ae51e867e4728d4f05c1 to your computer and use it in GitHub Desktop.
Save prosenjit-manna/ae51e867e4728d4f05c1 to your computer and use it in GitHub Desktop.
lazyload with jquery
$(window).on('DOMContentLoaded load resize scroll', function () {;
var images = $("#main-wrapper img[data-src]");
// load images that have entered the viewport
$(images).each(function (index) {
if (isElementInViewport(this)) {
$(this).attr("src",$(this).attr("data-src"));
$(this).removeAttr("data-src");
}
})
// if all the images are loaded, stop calling the handler
if (images.length == 0) {
$(window).off('DOMContentLoaded load resize scroll')
}
})
// source: http://stackoverflow.com/questions/123999/how-to-tell-if-a-dom-element-is-visible-in-the-current-viewport/7557433#7557433
function isElementInViewport (el) {
var rect = el.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= $(window).height() &&
rect.right <= $(window).width()
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment