From 68ef831d71a0b2384730ff974072576a441773ca Mon Sep 17 00:00:00 2001 From: ErtugKaya Date: Wed, 2 Jul 2014 03:47:20 +0300 Subject: [PATCH] Load only visible images ```$("img").trigger( "unveil" );``` checks if image is in view before loading. --- jquery.unveil.js | 36 ++++++++++++++++++++++-------------- 1 file changed, 22 insertions(+), 14 deletions(-) diff --git a/jquery.unveil.js b/jquery.unveil.js index 8cfeb25..838ce77 100644 --- a/jquery.unveil.js +++ b/jquery.unveil.js @@ -19,26 +19,34 @@ images = this, 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); + var isInView = function(e) { + 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; + } + + this.on("unveil", function(event) { + if (isInView($(this))) + { + 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).off(event); } }); 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; + return isInView($e); }); loaded = inview.trigger("unveil");