メインコンテンツまでスキップ

Webパフォーマンス最適化の実践的手法

· 約3分

Webサイトのパフォーマンスを向上させるための実践的な手法について解説します。
パフォーマンスはユーザーエクスペリエンスに直結する重要な要素です。この記事では、実践的な最適化手法を紹介します。

Core Web Vitalsの理解

Googleが定義するCore Web Vitalsは以下の3つの指標です。

Largest Contentful Paint (LCP)

最大のコンテンツが描画されるまでの時間です。

  • 目標: 2.5秒以内
  • 改善方法:
    • 画像の最適化
    • サーバーの応答時間改善
    • レンダリングブロッキングリソースの削減

First Input Delay (FID)

ユーザーの最初の操作に対する応答時間です。

  • 目標: 100ms以内
  • 改善方法:
    • JavaScriptの実行時間削減
    • コード分割
    • Web Workersの活用

Cumulative Layout Shift (CLS)

レイアウトの予期しない移動を測定します。

  • 目標: 0.1以下
  • 改善方法:
    • 画像や広告のサイズを事前に指定
    • フォントの最適化
    • 動的コンテンツの適切な配置

画像最適化

フォーマットの選択

<!-- WebPフォーマットの活用 -->
<picture>
<source srcset="image.webp" type="image/webp">
<source srcset="image.jpg" type="image/jpeg">
<img src="image.jpg" alt="説明文">
</picture>

レスポンシブ画像

<img 
src="small.jpg"
srcset="small.jpg 300w, medium.jpg 600w, large.jpg 1200w"
sizes="(max-width: 600px) 100vw, (max-width: 1200px) 50vw, 25vw"
alt="説明文"
>

JavaScriptの最適化

動的インポート

// 必要な時にのみモジュールを読み込み
async function loadChart() {
const { Chart } = await import('./chart.js');
return new Chart();
}

サービスワーカーの活用

// service-worker.js
self.addEventListener('fetch', event => {
if (event.request.destination === 'image') {
event.respondWith(
caches.match(event.request).then(response => {
return response || fetch(event.request);
})
);
}
});

CSS最適化

Critical CSSの実装

<!-- インライン化するCritical CSS -->
<style>
/* Above-the-fold content styles */
.header { /* styles */ }
.hero { /* styles */ }
</style>

<!-- 非同期読み込みCSS -->
<link rel="preload" href="styles.css" as="style" onload="this.onload=null;this.rel='stylesheet'">
<noscript><link rel="stylesheet" href="styles.css"></noscript>

ネットワーク最適化

リソースヒント

<!-- DNS prefetch -->
<link rel="dns-prefetch" href="//fonts.googleapis.com">

<!-- Preconnect -->
<link rel="preconnect" href="https://api.example.com">

<!-- Prefetch -->
<link rel="prefetch" href="/next-page.html">

<!-- Preload -->
<link rel="preload" href="critical-font.woff2" as="font" type="font/woff2" crossorigin>

パフォーマンス測定

Lighthouse CI

# .github/workflows/lighthouse.yml
name: Lighthouse CI
on: [push]
jobs:
lighthouse:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Run Lighthouse CI
run: |
npm install -g @lhci/cli@0.8.x
lhci autorun

Web Vitalsの測定

import { getCLS, getFID, getFCP, getLCP, getTTFB } from 'web-vitals';

getCLS(console.log);
getFID(console.log);
getFCP(console.log);
getLCP(console.log);
getTTFB(console.log);

まとめ

Webパフォーマンスの最適化は継続的な取り組みが必要です。定期的な測定と改善を行い、ユーザーにとって快適なWebサイトを提供しましょう。

コメント

コメントはまだありません