export let picLazyLoad = function(){
let observer = new IntersectionObserver(
(changes) => {
changes.forEach((change) => {
if(change.intersectionRatio > 0){
console.log(change.target)
var img = change.target;
img.src = img.dataset.src;
observer.unobserve(img);
}
})
}
)
Array.from(document.getElementsByClassName('cover')).forEach((item) => {
observer.observe(item);
})
}
將此方法導出,以便在不同的組件中可以使用。
componentDidMount = () => {
let self = this
this.context.getYoutubeData(picLazyLoad)
}
之後在componentDidMount生命週期中,獲取數據之後的回調中去調用該方法。此處一定要在頁面渲染之後再調用方法,否則獲取不到target。該方法的缺點是兼容性不高,兼容性如下圖: