图表的懒加载
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
|
attributeChanged(records) { let el, code records.forEach((record) => { if (record.attributeName === 'code') { el = record.target code = el.getAttribute('code') this.updateCharts(this.jjList[code], code) } }) }
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
|
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') } }) }
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) }) },
|
样例