diff --git a/index.html b/index.html index 0adb338..1fd2269 100644 --- a/index.html +++ b/index.html @@ -147,6 +147,23 @@
+ If you want to use more data-src options for a different purpose you can use the dataOptions parameter. + The dataOptions is an array of [function, data-attribute].
+
+ var dataOptions = [
+ [ function()
{ return window.innerWidth < 991; },
"data-src-small"
],
+ [ function()
{ return window.devicePixelRatio > 1; },
"data-src-retina"
]
+ ];
+
+
+ <img data-src-small="corgi.png" data-src-retina="corgiretina.png"data-src="normalcorgi.png" />
+
+ + The code gets a list of data-options. If the condition is valid, the code tries to get the value of the data attribute in the img tag. If it can't, tries with the next data attribute. +
+You can still trigger image loading whenever you need.
All you have to do is select the images you want to "unveil" and trigger the event:
diff --git a/jquery.unveil.js b/jquery.unveil.js index 8cfeb25..b418a7f 100644 --- a/jquery.unveil.js +++ b/jquery.unveil.js @@ -8,20 +8,25 @@ * https://github.com/luis-almeida */ -;(function($) { - - $.fn.unveil = function(threshold, callback) { +; (function ($) { + $.fn.unveil = function (threshold, dataOptions, callback) { var $w = $(window), - th = threshold || 0, - retina = window.devicePixelRatio > 1, - attrib = retina? "data-src-retina" : "data-src", - images = this, - loaded; - - this.one("unveil", function() { - var source = this.getAttribute(attrib); - source = source || this.getAttribute("data-src"); + th = threshold || 0, + images = this, + loaded, + attrib = []; + + dataSrcOptions(); + + this.one("unveil", function () { + var source = undefined; + attrib.every(element => { + source = this.getAttribute(element); + if (source) return false; + return true; + }) + if (source) { this.setAttribute("src", source); if (typeof callback === "function") callback.call(this); @@ -29,14 +34,14 @@ }); function unveil() { - var inview = images.filter(function() { + 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(); + wb = wt + $w.height(), + et = $e.offset().top, + eb = et + $e.height(); return eb >= wt - th && et <= wb + th; }); @@ -45,6 +50,22 @@ images = images.not(loaded); } + function isRetina() { + return window.devicePixelRatio > 1; + } + + function dataSrcOptions() { + dataOptions.push([isRetina, "data-src-retina"]); + if (dataOptions != undefined && dataOptions.length > 0) { + dataOptions.forEach(element => { + if (element != undefined && element.length > 1 && typeof element[0] === "function" && element[0]()) + attrib.push(element[1]); + }) + } + + attrib.push("data-src"); + } + $w.on("scroll.unveil resize.unveil lookup.unveil", unveil); unveil();