forked from luis-almeida/unveil
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jquery.unveil.js
76 lines (62 loc) · 1.99 KB
/
jquery.unveil.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/**
* jQuery Unveil
* A very lightweight jQuery plugin to lazy load images
* http://luis-almeida.github.com/unveil
*
* Licensed under the MIT license.
* Copyright 2013 Luís Almeida
* https://github.com/luis-almeida
*/
;(function($) {
$.fn.unveil = function(opts, callback) {
opts = opts || {
threshold: 0,
useBgImage: false,
isPictureElement: false
}
var $w = $(window),
th = opts.threshold,
useBgImage = opts.useBgImage,
isPictureElement = opts.isPictureElement,
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");
if (source) {
if (useBgImage) {
var currentValues = this.style.getPropertyValue("background-image");
var newValues = (!!currentValues ? currentValues + ", ": "") + "url(" + source + ")";
this.style.setProperty("background-image", newValues);
}
else
this.setAttribute("src", source);
if (typeof callback === "function") callback.call(this);
}
if (isPictureElement) {
$(this).find("source").each(function(index, elem) {
var source = $(elem).attr("data-src") || $(elem).attr("data-srcset")
$(elem).attr("srcset", source)
})
}
});
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);
}
$w.on("scroll.unveil resize.unveil lookup.unveil", unveil);
unveil();
return this;
};
})(window.jQuery || window.Zepto);