-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlazyload.js
More file actions
67 lines (58 loc) · 1.9 KB
/
lazyload.js
File metadata and controls
67 lines (58 loc) · 1.9 KB
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
/*Lazylaod插件,适用于jQuery和Zepto*/
/*author:chukuang(paoloo1995)*/
;(function(factory) {
if (typeof define === 'function' && define.amd) {
if (window.jQuery) {
define(['jquery'], factory)
} else if (window.Zepto) {
define(['zepto'], factory)
}
} else {
factory(window.jQuery || window.Zepto)
}
})(function($, undefined) {
var w = window;
function isInSight(element) {
var elementTop = element.getBoundingClientRect().top,
elementBottom = element.getBoundingClientRect().bottom,
viewHeight = document.documentElement.clientHeight,
elementHeight = element.scrollHeight;
if ((elementBottom < 0) || (elementTop > viewHeight + elementHeight)) {
return false;
} else {
return true;
}
}
function throttle(method, args) {
var delay = 200;
clearTimeout(method.id);
method.id = setTimeout(function() {
method(args);
}, delay);
}
function load($elements) {
$elements.each(function(index, item) {
var $item = $(item)
if (!$item.data('src') || ($item.data('load-status') === 'already')) {
return;
} else if (isInSight(item)) {
$item.attr('src', $item.data('src'));
$item.attr('load-status', 'already');
return;
}
});
}
if (!$.fn.hasOwnProperty('lazyload')) {
$.fn.lazyload = function() {
var $elements = this;
load($elements);
$(w).on('resize', function() {
throttle(load, $elements);
});
$(w).on('scroll', function() {
throttle(load, $elements);
})
return this;
}
}
})