实现原理
Vue-Lazyload使用了HTML的IntersectionObserver API来实现懒加载,该API可以监听元素是否在可视区域内,如果在可视区域内,则会触发加载图片的事件;若一开始元素不在可视区域内,随着滚动而滚动,当元素到达可视区域时,触发加载图片的事件。
核心源码
// This is the component to implement lazyloading
Vue.component('lazyimg', {
props: {
src:{
type:String,
required:true
}
},
data() {
return {
observer: null,
intersected: false
};
},
template: '<img :src="intersected ? src : ''" :data-src="src" />',
mounted() {
// create an intersection observer instance
this.observer = new IntersectionObserver(
entries => {
// when element is intersecting, set intersected to true
if (entries[0].isIntersecting) {
this.intersected = true;
// stop observing when intersected
this.observer.unobserve(this.$el);
}
},
// options
{ rootMargin: "50px 0px"}
);
// observe the current element
this.observer.observe(this.$el);
// unobserve on beforeDestroy
this.$once("hook:beforeDestroy", () =>
this.observer.unobserve(this.$el)
);
}
});