📚 프론트엔드 공부 일지/REACT

이미지 레이지 로딩

wei3on 2024. 7. 30. 12:54

 

? Image Lazy Loadinig

이미지가 실제로 보일 필요가 있을 때 로딩을 할 수 있게 하는 테크닉

 

구현 할 수 있는 방법 세가지

  1. 자바스크립트 이벤트
  2. Intersection observer
  3. 브라우저 Native Loading 이용 -> loading 속성 이용

 

브라우저 Native Loading

const LazyImage = ({ url, alt }) => {
  const [isLoading, setIsLoading] = useState(true)
  const [opacity, setOpacity] = useState('opacity-0')

  useEffect(() => {
    isLoading ? setOpacity('opacity-0') : setOpacity('opacity-100')
  }, [isLoading])
  

  return (
    <>
      {isLoading && (
        <div className="absolute h-full z-10 w-full flex items-center justify-center">
          ...loading
        </div>
      )}
      <img 
        src={url}
        alt={alt}
        width= "100%"
        height="auto"
        loading="lazy"
        onLoad={() => setIsLoading(false)}
        className={`object-contain h-full ${opacity}`}
      />
    </>
  )
}

img 속성 중에 loading="lazy" 와 onLoad 속성을 이용해서 lazy loading 구현