File tree Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change
1
+ // https://developer.mozilla.org/zh-CN/docs/Web/API/IntersectionObserver
2
+ // http://www.ruanyifeng.com/blog/2016/11/intersectionobserver_api.html
3
+ // 懒加载原理
4
+
5
+ var io = new IntersectionObserver ( callback , option ) ;
6
+ // 开始观察
7
+ io . observe ( document . getElementById ( 'example' ) ) ;
8
+ // 停止观察
9
+ io . unobserve ( element ) ;
10
+ // 关闭观察器
11
+ io . disconnect ( ) ;
12
+
13
+ // 多节点监听
14
+ io . observe ( elementA ) ;
15
+ io . observe ( elementB ) ;
16
+
17
+
18
+ // 实例:惰性加载(lazy load)
19
+ function query ( selector ) {
20
+ return Array . from ( document . querySelectorAll ( selector ) ) ;
21
+ }
22
+
23
+ var observer = new IntersectionObserver (
24
+ function ( changes ) {
25
+ changes . forEach ( function ( change ) {
26
+ var container = change . target ;
27
+ var content = container . querySelector ( 'template' ) . content ;
28
+ container . appendChild ( content ) ;
29
+ observer . unobserve ( container ) ;
30
+ } ) ;
31
+ }
32
+ ) ;
33
+
34
+ query ( '.lazy-loaded' ) . forEach ( function ( item ) {
35
+ observer . observe ( item ) ;
36
+ } ) ;
You can’t perform that action at this time.
0 commit comments