Lazy loading images that are not in the viewport improves initial page load performance and user experience. This is an in-depth guide to everything about lazy loading of images including native lazy loading methods.
// lazy.js
export default function (Vue) {
Vue.directive('lazy', {
mounted(el, { value }) {
if (/\S+/.test(value)) {
const observer = new IntersectionObserver(entries => {
entries.forEach(entry => {
if (entry && entry.isIntersecting) {
if (el.tagName == 'IMG') {
el.src = value;
} else {
el.style.backgroundImage = `url("${value}")`;
}
observer.disconnect();
}
});
});
observer.observe(el);
el.$lazy = observer;
}
},
beforeUnmount(el) {
if (el.$lazy) {
el.$lazy.unobserve(el);
}
}
});
};
import { createApp } from "vue";
import Lazy from './lazy';
// global register
const app = createApp(App)
.use(Lazy)
.mount("#app");
<img class="placeholder" v-lazy="https://unsplash.com/photos/al1bUu7EfAQ/download?force=true&w=1920">