1. 시작하기 전에
이 Codelab에서는 web-vitals
JavaScript 라이브러리를 사용하여 웹페이지의 코어 웹 바이탈을 측정하는 방법을 알아봅니다.
Google에서는 핵심 성능 보고서를 측정하고 모바일 및 데스크톱 기기에서 분류된 페이지 로드의 75번째 백분위수 내에 포함되도록 하는 것이 좋습니다.
핵심 성능 보고서에는 모든 웹페이지에 적용되며 사용자 환경에 관한 중요한 통계를 제공하는 다음 세 가지 측정항목이 포함됩니다.
- 최대 콘텐츠 렌더링 시간 (LCP) 로드 성능을 측정하며 페이지가 로드되기 시작한 후 2.5초 이내에 발생해야 합니다.
- 다음 페인트에 대한 상호작용 (INP). 상호작용을 측정하며 200밀리초 이내에 발생해야 합니다.
- 누적 레이아웃 변경 (CLS) 시각적 안정성을 측정하며 0.1 이내여야 합니다.
기본 요건
실행할 작업
web-vitals
라이브러리를 웹페이지에 추가합니다.- Google Chrome 개발자 도구에서 웹페이지의 코어 웹 바이탈을 측정합니다.
- 선택사항: 웹페이지의 코어 웹 바이탈을 Google 애널리틱스에 보고합니다.
필요한 항목
- 원하는 텍스트 편집기(예: Sublime Text, Visual Studio Code)
- Chromium 기반 웹브라우저(예: Chrome, Microsoft Edge)(Chromium 기반 웹브라우저가 필요한 이유에 관한 자세한 내용은 브라우저 지원을 참고하세요.)
2. 웹페이지에 web-vitals 라이브러리 추가
- 텍스트 편집기에서
web-vitals-test.html
파일을 만든 다음 파일에 다음 HTML 코드를 입력합니다.
web-vitals-test.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Web Vitals Test</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<p><img style="max-width: 360px" src="https://placekitten.com/g/3840/2160" alt="Kitten" /></p>
<p>Text below image</p>
</body>
</html>
이 코드는 이 Codelab에서 사용할 웹페이지를 만듭니다.
- 두 번째
<p>
요소 뒤의 HTML 코드의<body>
요소에 이 모듈 스크립트를 입력한 다음 파일을 저장합니다.
web-vitals-test.html
<script type="module">
import {onCLS, onINP, onLCP} from 'https://unpkg.com/web-vitals@4?module';
onCLS(console.log);
onINP(console.log);
onLCP(console.log);
</script>
이 모듈 스크립트는 콘텐츠 전송 네트워크에서 web-vitals
라이브러리를 로드합니다. 이제 파일이 다음 코드 스니펫과 같이 표시됩니다.
web-vitals-test.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Web Vitals Test</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<p><img style="max-width: 360px" src="https://placekitten.com/g/3840/2160" alt="Kitten" /></p>
<p>Text below image</p>
<script type="module">
import {onCLS, onINP, onLCP} from 'https://unpkg.com/web-vitals@4?module';
onCLS(console.log);
onINP(console.log);
onLCP(console.log);
</script>
</body>
</html>
모든 최신 브라우저는 모듈 스크립트를 지원하며, 모듈 스크립트는 코어 웹 바이탈을 측정하는 데 필요한 API와 같은 새로운 API만 사용하는 코드에 적합합니다. 모듈이나 코어 웹 바이탈 API를 지원하지 않는 브라우저는 이 스크립트를 로드하지 않습니다.
3. Google Chrome 개발자 도구에서 웹페이지의 코어 웹 바이탈 측정
- 웹브라우저에서 저장된 파일을 엽니다.
- 웹페이지를 마우스 오른쪽 버튼으로 클릭한 다음 대화상자에서 검사를 클릭합니다.
- Google Chrome 개발자 도구 창에서 콘솔 탭을 클릭한 다음 콘솔 설정
> 로그 보존을 선택합니다. 이 설정은 웹페이지를 새로고침할 때 로그가 유지되도록 합니다.
- 네트워크 탭을 클릭한 다음 제한 드롭다운 메뉴의
펼치기 화살표를 클릭하고 느린 3G를 선택합니다. 이 설정은 느린 네트워크 연결을 시뮬레이션합니다.
- 콘솔 탭으로 돌아간 다음 웹페이지의 아무 곳이나 클릭합니다. LCP 측정항목이 콘솔 탭에 출력됩니다.
- 웹페이지를 새로고침합니다. CLS 측정항목은 콘솔 탭에 출력됩니다.
- 네트워크 탭으로 돌아간 다음 제한 드롭다운 메뉴의
펼치기 화살표를 클릭하고 빠른 3G를 선택합니다. 이 설정은 빠른 네트워크 연결을 시뮬레이션합니다.
- 콘솔 탭으로 돌아간 후 웹페이지의 아무 곳이나 클릭합니다.LCP 측정항목이 콘솔 탭에 다시 인쇄되지만 이전보다 개선되었습니다.
- 웹페이지를 새로고침합니다. CLS 측정항목이 콘솔 탭에 다시 인쇄되지만 이전보다 개선되었습니다.
4. 선택사항: 웹페이지의 코어 웹 바이탈을 Google 애널리틱스에 보고
- 모듈 스크립트의 가져오기 문 뒤에 있는
web-vitals-test.html
파일에 이sendToGoogleAnalytics()
함수를 입력한 다음 파일을 저장합니다.
web-vitals-test.html
function sendToGoogleAnalytics({name, delta, id}) {
// Assumes the global `gtag()` function exists, see:
// https://developers.google.com/analytics/devguides/collection/gtagjs
gtag('event', name, {
event_category: 'Web Vitals',
// Google Analytics metrics must be integers, so the value is rounded.
// For CLS the value is first multiplied by 1000 for greater precision
// (note: increase the multiplier for greater precision if needed).
value: Math.round(name === 'CLS' ? delta * 1000 : delta),
// The `id` value will be unique to the current page load. When sending
// multiple values from the same page (e.g. for CLS), Google Analytics can
// compute a total by grouping on this ID (note: requires `eventLabel` to
// be a dimension in your report).
event_label: id,
// Use a non-interaction event to avoid affecting bounce rate.
non_interaction: true,
});
}
onCLS(sendToGoogleAnalytics);
onINP(sendToGoogleAnalytics);
onLCP(sendToGoogleAnalytics);
이 코드는 Core Web Vitals를 Google 애널리틱스로 전송하며, Google 애널리틱스에서 '주요 이벤트' 보고서를 통해 확인할 수 있습니다.
이제 파일이 다음 코드 스니펫과 같이 표시됩니다.
web-vitals-test.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Web Vitals Test</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<p><img style="max-width: 360px" src="https://placekitten.com/g/3840/2160" alt="Kitten" /></p>
<p>Text below image</p>
<script type="module">
import {onCLS, onINP, onLCP} from 'https://unpkg.com/web-vitals@4?module';
function sendToGoogleAnalytics({name, delta, id}) {
// Assumes the global `gtag()` function exists, see:
// https://developers.google.com/analytics/devguides/collection/gtagjs
gtag('event', name, {
event_category: 'Web Vitals',
// Google Analytics metrics must be integers, so the value is rounded.
// For CLS the value is first multiplied by 1000 for greater precision
// (note: increase the multiplier for greater precision if needed).
value: Math.round(name === 'CLS' ? delta * 1000 : delta),
// The `id` value will be unique to the current page load. When sending
// multiple values from the same page (e.g. for CLS), Google Analytics can
// compute a total by grouping on this ID (note: requires `eventLabel` to
// be a dimension in your report).
event_label: id,
// Use a non-interaction event to avoid affecting bounce rate.
non_interaction: true,
});
}
onCLS(sendToGoogleAnalytics);
onINP(sendToGoogleAnalytics);
onLCP(sendToGoogleAnalytics);
</script>
</body>
</html>
5. 축하합니다
축하합니다. web-vitals
라이브러리를 사용하여 웹페이지의 Core Web Vitals를 측정하고 보고하는 방법을 배웠습니다.