Skip to content

Instantly share code, notes, and snippets.

@MohitTilwani15
Created March 31, 2019 21:39
Show Gist options
  • Save MohitTilwani15/9ecdd81613fe9eaffc244c45c95e915d to your computer and use it in GitHub Desktop.
Save MohitTilwani15/9ecdd81613fe9eaffc244c45c95e915d to your computer and use it in GitHub Desktop.
Lazy load images using Intersection Observer
<template>
<img ref='image' :alt="title" />
</template>
<script lang="ts">
export default {
name: 'VueImage',
props: {
imageSrc: {
type: String,
default: '',
},
title: {
type: String,
default: '',
},
},
data() {
return {
observer: null,
};
},
mounted() {
if (window.IntersectionObserver) {
this.handleObserver();
} else {
this.$refs.image.src = this.imageSrc;
}
},
methods: {
setBgImage(entries) {
entries.forEach((entry) => {
if (entry.intersectionRatio > 0) {
this.$refs.image.src = this.imageSrc;
this.observer.disconnect();
}
});
},
handleObserver() {
this.observer = new IntersectionObserver(this.setBgImage, { rootMargin: '0px', threshold: 0.1 });
this.observer.observe(this.$refs.image);
},
},
beforeDestroy() {
this.observer = null;
},
};
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment