-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
116 lines (82 loc) · 2.71 KB
/
main.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
( function () {
var lazyLoadImg = function() {
var observer = null;
var ioConfig = {
root: null,
rootMargin: '150px 0px 0px 0px',
threshold: [ 0.2 ]
};
var elmsSelector = 'img[data-src]';
/**
* Initialize Lazy Loading
*
* @param {Object} config
*/
var init = function( config ) {
if ( 'undefined' === typeof config ) {
config = {};
}
if ( config.selector ) {
selector = config.selector;
}
if ( config.ioConfig ) {
ioConfig = mergeObj( ioConfig, config.ioConfig );
}
onContentLoad = onContentLoad.bind( this );
onIntersect = onIntersect.bind( this );
initIO();
if ( 'loading' === document.readyState ) {
document.addEventListener( 'DOMContentLoaded', onContentLoad );
} else {
onContentLoad();
}
};
/**
* Merge object
*
* @param {Object} obj1 Default object.
* @param {Object} obj2 User given object.
*
* @returns {Object}
*/
var mergeObj = function( obj1, obj2 ) {
var keys = Object.keys( obj2 );
for ( var l = 0; l < keys.length; l++ ) {
if ( keys[l] in obj2 ) {
obj1[ keys[l] ] = obj2[ keys[l] ];
}
}
return obj1;
}
var onContentLoad = function() {
var elms = document.querySelectorAll( elmsSelector );
for( var i = 0; i < elms.length; i++ ) {
observer.observe( elms[i] );
}
}
var initIO = function() {
observer = new IntersectionObserver( onIntersect, ioConfig );
}
var onIntersect = function( entries ) {
for( var j = 0; j < entries.length; j++ ) {
if ( entries[j].intersectionRatio > 0 ) {
// Stop watching and load the image
observer.unobserve(entries[j].target);
var imgSrc = entries[j].target.dataset.src;
preLoadImage(entries[j].target, imgSrc);
}
}
}
var preLoadImage = function( imgElm, imgSrc ) {
var img = new Image();
img.onload = function() {
imgElm.src = img.src;
}
img.src = imgSrc;
}
return {
init: init
};
}
window.lazyLoadImg = new lazyLoadImg();
} () );