-
-
Save MohitTilwani15/9ecdd81613fe9eaffc244c45c95e915d to your computer and use it in GitHub Desktop.
Lazy load images using Intersection Observer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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