From d9f27087cad28e52dc504c019965654fc4c4f8a7 Mon Sep 17 00:00:00 2001 From: Mashhood Rastgar Date: Wed, 10 Dec 2014 10:38:41 +0500 Subject: [PATCH] added option for delay The image downloading starts after a delay (in ms), so if the user scroll past several images to see the ones at the end, it will load only those at the end. --- jquery.unveil.js | 75 +++++++++++++++++++++++++++--------------------- 1 file changed, 42 insertions(+), 33 deletions(-) diff --git a/jquery.unveil.js b/jquery.unveil.js index 8cfeb25..e6346e6 100644 --- a/jquery.unveil.js +++ b/jquery.unveil.js @@ -10,47 +10,56 @@ ;(function($) { - $.fn.unveil = function(threshold, callback) { + $.fn.unveil = function(threshold, definedDelay, callback) { - var $w = $(window), - th = threshold || 0, - retina = window.devicePixelRatio > 1, - attrib = retina? "data-src-retina" : "data-src", - images = this, - loaded; + var $w = $(window), + th = threshold || 0, + retina = window.devicePixelRatio > 1, + attrib = retina? "data-src-retina" : "data-src", + images = this, + delay = definedDelay || 0, + lastScroll = (new Date()).getTime(), + loaded; - this.one("unveil", function() { - var source = this.getAttribute(attrib); - source = source || this.getAttribute("data-src"); - if (source) { - this.setAttribute("src", source); - if (typeof callback === "function") callback.call(this); - } - }); + this.one("unveil", function() { + var source = this.getAttribute(attrib); + source = source || this.getAttribute("data-src"); + if (source) { + this.setAttribute("src", source); + if (typeof callback === "function") callback.call(this); + } + }); - function unveil() { - var inview = images.filter(function() { - var $e = $(this); - if ($e.is(":hidden")) return; + function unveil() { + if(((new Date()).getTime() - lastScroll) < delay) + return; // do not process if the page has scrolled again since last time + + 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(); + var wt = $w.scrollTop(), + wb = wt + $w.height(), + et = $e.offset().top, + eb = et + $e.height(); - return eb >= wt - th && et <= wb + th; - }); + return eb >= wt - th && et <= wb + th; + }); - loaded = inview.trigger("unveil"); - images = images.not(loaded); - } + loaded = inview.trigger("unveil"); + images = images.not(loaded); + } - $w.on("scroll.unveil resize.unveil lookup.unveil", unveil); + $w.on("scroll.unveil resize.unveil lookup.unveil", function () { + lastScroll = (new Date()).getTime(); + setTimeout(unveil, delay); + }); - unveil(); + setTimeout(unveil, delay); - return this; - - }; + return this; + }; })(window.jQuery || window.Zepto); + +