프론트엔드/Vue

img lazyload 만들기(이미지 지연로딩)

짱구를왜말려? 2022. 10. 23. 14:41
반응형
SMALL

# What?

해당 스크롤이 이미지쪽에 가까워지면 이미지 불러오는 방식

 

# How?

@ LazyImg.vue

<template>
    <img :data-lazy="src" alt="" ref="el">
</template>
<script>
export default {
    props: ["src"],

    methods: {

        callIntersectionApi() {
            let self = this;

            const options = {
                root: null,
                threshold: 0.5,
                rootMargin: '0px'
            };

            const lazyLoadCallback = (entries, observer) => {
                entries.forEach(entry => {
                    if (entry.isIntersecting) {
                        // 감지대상이 교차영역에 진입 할 경우
                        console.log(entry);
                        self.imageLoad(entry.target);
                        observer.unobserve(entry.target);
                    }
                });
            };

            const lazyLoadingIO = new IntersectionObserver(lazyLoadCallback, options);

            lazyLoadingIO.observe(this.$refs.el);
        },

        imageLoad() {
            const imgElement = this.$refs.el;
            // data-lazy 에 지정된 이미지 경로를 <img src=""> 에 셋팅 합니다.
            imgElement.setAttribute('src', imgElement.getAttribute('data-lazy'));

            imgElement.onload = function () {
                imgElement.removeAttribute('data-lazy');
            };

        }
    },

    mounted() {
        window.IntersectionObserver ? this.callIntersectionApi() : this.imageLoad();
    }
}
</script>

@ 사용하는곳.vue

...
<lazy-img src="http://test.jpg" />
...

* 참고 url : https://archijude.tistory.com/484

LIST