From 2d0efd11cfa1c364623506e12be71bcd342979b6 Mon Sep 17 00:00:00 2001 From: Raja Kapur Date: Tue, 9 Jun 2015 19:30:55 -0400 Subject: [PATCH] Added debouncing for scroll event https://developers.google.com/web/fundamentals/performance/rendering/debounce-your-input-handlers?hl=en --- jquery.unveil.js | 41 ++++++++++++++++++++++++++--------------- 1 file changed, 26 insertions(+), 15 deletions(-) diff --git a/jquery.unveil.js b/jquery.unveil.js index 8cfeb25..7683733 100644 --- a/jquery.unveil.js +++ b/jquery.unveil.js @@ -17,7 +17,8 @@ retina = window.devicePixelRatio > 1, attrib = retina? "data-src-retina" : "data-src", images = this, - loaded; + loaded, + timer; this.one("unveil", function() { var source = this.getAttribute(attrib); @@ -29,20 +30,30 @@ }); function unveil() { - var inview = images.filter(function() { - var $e = $(this); - if ($e.is(":hidden")) return; - - var wt = $w.scrollTop(), - wb = wt + $w.height(), - et = $e.offset().top, - eb = et + $e.height(); - - return eb >= wt - th && et <= wb + th; - }); - - loaded = inview.trigger("unveil"); - images = images.not(loaded); + if (timer) { + window.clearTimeout(timer); + } + + timer = window.setTimeout(function() { + // there were no more images on the entire page + // no need to keep trying + if (images.length == 0) return; + + var inview = images.filter(function() { + var $e = $(this); + if ($e.is(":hidden")) return; + + var wt = $w.scrollTop(), + wb = wt + $w.height(), + et = $e.offset().top, + eb = et + $e.height(); + + return eb >= wt - th && et <= wb + th; + }); + + loaded = inview.trigger("unveil"); + images = images.not(loaded); + }, 50); } $w.on("scroll.unveil resize.unveil lookup.unveil", unveil);