[프론트엔드 최적화] 손쉽게 이미지 용량 줄이기

2022. 4. 5. 20:28
반응형

https://squoosh.app/

 

Squoosh

Simple Open your image, inspect the differences, then save instantly. Feeling adventurous? Adjust the settings for even smaller files.

squoosh.app

 

위 사이트(squoosh)에 접속해서 손쉽게 이미지 용량을 줄일 수 있다.

 

 

우측의 quality, width, height 등을 조정하면 된다.

좌측이 비포, 우측이 애프터로 양쪽을 비교하며 수치를 조정할 수 있다.

 

예시 사진으로는 육안으로는 확인하기 힘들 정도로 미미한 화질 저하만 일어났는데,

용량은 무려 3.78mb에서 40.9kb로 99% 감소시킬 수 있었다.

 

 

조금이라도 더 적은 용량, 조금이라도 더 나은 화질을 원한다면 확장자를 webP로 설정해준다.

(*webP는 구글이 개발한 손실/비손실 압축 이미지 파일을 위한 이미지 포맷)

 

 

 


하지만...

webP가 효율적인 이미지 포맷이긴 하지만, 브라우저에 따라 지원하지 않는 경우가 있다.

 

이럴 땐 <picture>태그를 사용하여 webP라는 확장자를 가진 이미지를 불러올 수 있으면 이를 사용하고, 

만약 그렇지 않다면 jpg를 사용하도록 추가 작업을 해주어 해결할 수 있다.

 

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/picture

 

<picture>: The Picture element - HTML: HyperText Markup Language | MDN

The <picture> HTML element contains zero or more <source> elements and one <img> element to offer alternative versions of an image for different display/device scenarios.

developer.mozilla.org

 

<picture>
  //webP를 로드할 수 있으면 이를 사용하고
  <source srcset="logo.webp" type="image/webp">
  
  //그게 아니라면 png 이미지를 사용해라
  <img src="logo.png" alt="logo">
</picture>

 

위와 같은 picture 태그에 이전 포스팅에서 살펴보았던 lazy loading을 적용하려면,

소스코드를 아래와 같이 수정해준다.

 

 

//컴포넌트 props로 webp추가
<Card webp={main3_webp} image={main3}>
  카드 텍스트
</Card>,

 

 

  useEffect(() => {
    const options = {};

    const callback = (entries, observer) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          entry.target.src = entry.target.dataset.src;
          
          //코드 추가
          entry.target.previousSibling.srcset =
            entry.target.previousSibling.dataset.srcset;

          observer.unobserve(entry.target);
        }
      });
      
      return (
      	...
      <picture>
        <source data-srcset={props.webp} type="image/webp" />
        <img data-src={props.image} ref={imgRef} />
      </picture>
        ...
      )
    };

 

 

반응형

BELATED ARTICLES

more