-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsmart-lazy-load.js
74 lines (68 loc) · 2.58 KB
/
smart-lazy-load.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
(function($) {
jQuery.fn.smartLazyLoad = function (sittings) {
var elements = this;
var screenHeight = window.innerHeight;
var screenWidth = window.innerWidth;
try {
var offsetLoad = sittings.offsetLoad?sittings.offsetLoad:0;
} catch (e) {
var offsetLoad = 0;
}
$().ready( function(e) {
var top = $(document).scrollTop();
$.each(elements, function(k, v){
checkLoad(top, v);
});
$( window ).resize(function() {
var top = $(document).scrollTop();
screenHeight = window.innerHeight;
screenWidth = window.innerWidth;
$.each(elements, function(k, v){
$(v).attr({"data-loaded":false});
checkLoad(top, v);
});
});
$(window).scroll( function(e) {
var top = $(document).scrollTop();
$.each(elements, function(k, v){
checkLoad(top, v);
});
});
});
function checkLoad(top, element) {
var offset = $(element).offset();
var ready = $(element).attr("data-loaded") ? $(element).attr("data-loaded") : false;
if(ready === "false") {
ready = false;
}
if(offset.top > (top-offsetLoad) && offset.top < (top+screenHeight+offsetLoad) && !ready) {
loadImage(element);
}
}
function loadImage(element) {
var defaultImage = $(element).attr("data-src");
var currentImage = false;
var srcset = $(element).attr("data-srcset");
if(srcset) {
var arSrcset = srcset.split(",");
if(arSrcset.length) {
var pre_size = 0;
$.each(arSrcset, function (k, v) {
var set = v.match(/\s?(.*)\s(\d*)w/);
if(set) {
console.log(pre_size, set[2], "<=", screenWidth, (set[2] >= screenWidth));
if(set[2] <= screenWidth) {
currentImage = set[1];
pre_size = set[2];
}
}
});
}
}
if(!currentImage) {
currentImage = defaultImage;
}
$(element).attr({src:currentImage}).attr({"data-loaded":true}).css({"opacity":"1"});
}
};
}) (jQuery);