Lazy loading images use IntersectionObserver and Vue.JS

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.

Create Lazy Loading Images Directive in Vue 3

// 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">

Github: https://github.com/Morioh-Lab/v-lazy 

#vue #javascript 

Lazy loading images use IntersectionObserver and Vue.JS
24.70 GEEK