ReactMasters / study

스터디 기록
1 stars 0 forks source link

11월 2주차 lighthouse 초안 #31

Open jordan-choi opened 2 years ago

jordan-choi commented 2 years ago

Lighthouse를 이용하여 퍼포먼스 최적화하기(feat. Chrome DevTool)

[Google I/O '18 Web performance made easy](https://youtu.be/Mv-l3-tJgGk) 발표를 참고하였습니다.

이 포스트는 Lighthouse와 Chrome DevTool을 이용하여 퍼포먼스를 최적화하는 방법에 대해서 다루었습니다.

불필요한 리소스 줄이기

브라우저에 보낼 웹페이지 리소스를 줄이기 위해, js와 css코드의 크기를 축소(minify)합니다. Minification(also called minimization)은 소스코드의 기능을 바꾸지 않고 소스코드에서 불필요한 characters를 제거하는 과정입니다. 여기서 불필요한 characters란 whitespace( ` ), newline(\n), comments(//,/,/), block delimeters({,}`) 등을 말합니다.

  1. Minify JavaScript

Untitled

위의 스크린샷과 같이 아무런 처리를 하지 않고 웹팩으로 빌드할 시, 번들링한 js파일의 용량은 큽니다(1.33MB).

webpack5에서 권장하는 terser-webpack-plugin을 사용해보겠습니다.

const TerserPlugin = require('terser-webpack-plugin');

module.exports = {
  optimization: {
    minimize: true,
    minimizer: [new TerserPlugin({ ... })],
  },
};

아래 스크린샷을 보면, js파일 용량이 1.33MB에서 1.23MB로 줄어든 것을 확인할 수 있습니다.

Untitled

  1. Minify CSS

MiniCssExtractPlugin은 CSS를 style 태그가 아닌 별도의 css 파일로 만들어줍니다.

const MiniCssExtractPlugin = require('mini-css-extract-plugin');

module.exports = {
  plugins: [new MiniCssExtractPlugin({
      linkType: false,
    filename: '[name].css',
  })],
  module: {
    rules: [
      {
        test: /\.css$/i,
        use: [MiniCssExtractPlugin.loader, "css-loader"],
      },
    ],
  },
};

Untitled

사용하지 않는 JavaScript, CSS 코드 제거하기

코드 커버리지는 테스트 시 실행된 코드의 비율을 말합니다. 코드 커버리지를 높이면 장기적인 관점에서 코드 결함을 감소시킨다는 경험적인 결론이 있습니다.

Chrome DevTools의 Coverage탭에서 CSS와 JS 코드의 코드 커버리지를 분석할 수 있습니다. 사용하지 않는 코드를 제거하면 페이지 로드 속도를 높일 수 있으며 모바일 유저의 셀룰러 데이터 사용량을 줄일 수 있습니다.

1

2

app.css파일의 경우, code coverage를 참고하여 사용되지 않는 css 선택자를 제거합니다.

Network payload 줄이기(불필요한 다운로드 제거하기)

const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');

module.exports = {
    plugins: [
        new BundleAnalyzerPlugin({ ... }),
    ],
}

JavaScript Boot-up time 줄이기

JavaScript boot-up time은 js파일을 다운로드하고 (network), 자바스크립트 엔진에서 parse, compile, execute하는 시간을 모두 합한 지연시간을 말합니다.

JavaScript processing([https://developers.google.com/web/updates/2018/08/web-performance-made-easy#lower_javascript_boot-up_time_with_code_splitting](https://developers.google.com/web/updates/2018/08/web-performance-made-easy#lower_javascript_boot-up_time_with_code_splitting))

Code Splitting

Lazy loading

웹 폰트 최적화하기

Google Font를 사용하면 페이지 로드 지연시간이 필연적으로 증가합니다. Lighthouse의 Opportunities audit에서도 Google Font와 관련하여 render-blocking resources를 제거할 시 460ms 만큼 페이지 로드 지연시간을 줄일 수 있다고 말하고 있습니다. render-blocking resources는 페이지가 Google Fonts 서버(fonts.googleapis.com)에서 CSS 파일을 fetch하기 이전까지 로드되지 못함을 의미합니다.

1

또한 Lighthouse의 Diagnostics audit을 보면 Avoid chaining critical requests을 권하고 있습니다. Critical request chain은 페이지 렌더링에서 우선순위가 높은 네트워크 요청 시리즈입니다. 이를 줄이기 위해 critical resources의 수를 줄이거나, 크기를 줄이거나, 순서를 최적화해야합니다.

2

Google Fonts를 최적화하기 위해 <link rel="stylesheet" /> 대신 font-face 속성으로 Google Fonts를 사용하겠습니다.

Resources are blocking the first paint of your page. Consider delivering critical JS/CSS inline [emphasis added] and deferring all non-critical JS/styles.

@font-face {
    font-family: 'Noto Sans KR';
    font-style: normal;
    font-weight: 400;
    font-display: swap;
    src: local("Noto Sans KR Regular"),
                url(./assets/fonts/NotoSansKr/NotoSansKR-Regular.woff2) format('woff2'),
        url(./assets/fonts/NotoSansKr/NotoSansKR-Regular.woff) format('woff');
}

@font-face {
    font-family: 'Noto Sans KR';
    font-style: normal;
    font-weight: 700;
    font-display: swap;
    src: local("Noto Sans KR Bold"),
                url(./assets/fonts/NotoSansKr/NotoSansKR-Bold.woff2) format('woff2'),
        url(./assets/fonts/NotoSansKr/NotoSansKR-Bold.woff) format('woff');
}

참고자료

https://developers.google.com/web/updates/2018/05/lighthouse

https://blog.logrocket.com/terser-vs-uglify-vs-babel-minify-comparing-javascript-minifiers/

https://testing.googleblog.com/2020/08/code-coverage-best-practices.html?m=1

https://developer.chrome.com/docs/devtools/coverage/

https://johnfraney.ca/posts/2019/12/09/improve-page-speed-google-fonts/

[https://developers.google.com/web/fundamentals/performance/optimizing-javascript/tree-shaking](