Skip to content

Commit

Permalink
added option for delay
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
mashhoodr committed Dec 10, 2014
1 parent ea75702 commit d9f2708
Showing 1 changed file with 42 additions and 33 deletions.
75 changes: 42 additions & 33 deletions jquery.unveil.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);


0 comments on commit d9f2708

Please sign in to comment.