图表类型的页面懒加载

图表的懒加载

MutationObserver的作用

检测dom的attr的变化,如果发生变化,就根据其变化状态决定是否加载

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
/**
* @function attributeChanged
* @param {Object} records dom观察的回调,被修改的dom信息
* @return {void}
* @description 被修改属性后调用来进行加载
*/
attributeChanged(records) {
let el, code
records.forEach((record) => {
// 如果code发生变化,则此时动态加载其对应的echarts图表
if (record.attributeName === 'code') {
el = record.target
code = el.getAttribute('code')
this.updateCharts(this.jjList[code], code)
}
})
}
/**
* @function initMutationObserver
* @return {void}
* @description 初始化dom观察
*/
initMutationObserver() {
const config = {
attributes: true,
}
this.mo = new MutationObserver(this.attributeChanged)
const els = document.querySelectorAll('.row')
els.forEach((el) => {
this.mo.observe(el, config)
})
}

IntersectionObserver的作用

浏览器用于异步检测某个元素相对于另一个元素的视口的可见性的观察,当检测到对应的echarts图表已经有一半滚入了外部容器的视口中,则触发修改其attr的变化

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
/**
* @function changeAttribute
* @param {Object} els 交错观察的回调,交错状态到达阈值的元素
* @return {void}
* @description 修改其属性值
*/
changeAttribute(els) {
let dom
let shouldLoad
els.forEach((el) => {
dom = el.target
shouldLoad =
el.intersectionRatio > this.limit &&
dom.hasAttribute('lazy-code')
// 到了要展示的阈值,并且尚未进行过展示
if (shouldLoad) {
dom.setAttribute('code', dom.getAttribute('lazy-code'))
dom.removeAttribute('lazy-code')
}
})
}
/**
* @function initIntersectionObserver
* @return {void}
* @description 初始化交错观察
*/
initIntersectionObserver() {
const config = {
root: document.querySelector('#root'),
threshold: [this.limit], // 若划过阈值点,再行加载
}
this.io = new IntersectionObserver(this.changeAttribute, config)
const els = document.querySelectorAll('.row')
els.forEach((el) => {
this.io.observe(el)
})
},

样例

{{item.name}}