この記事でわかること(実測データ&改善コード付き)
- Rustrak の Web Vitals 計測で スコア 70(Failed)・LCP 3.50s / TTFB 4.92s を検知した際の生データと 5 つの原因
- Astro の
build.inlineStylesheets: 'always'とastro-purgecssが競合して HTML が 264 KB に膨張した罠と解決実装public/_headers・WebP プリロード・動画 / GTM / RUM 遅延・過大画像リサイズ・Sentry 本番限定の実コード- デスクトップ LCP 156 ms、モバイル(Fast 3G / CPU 4x)LCP 230 ms までの Before / After 実測と Cloudflare 確認項目
「Astro の静的サイトを Cloudflare Pages で配信しているから速いはず」——そう考えていた当サイト(www.diverstage.biz)に、シリーズ第 1 回の Rustrak×Astroで軽量セルフホスト監視|Sentry代替構築ガイド の構成を導入したところ、実ユーザー計測(RUM)の Web Vitals 画面に表示されたのは「Failed(スコア 70)」という結果でした。
シリーズ完結編の本記事では、Rustrak の計測値から 5 つのボトルネックを特定し、**最大のハマりどころだった「PurgeCSS × インライン CSS の実行順序問題」**を解決して、モバイル Fast 3G でも LCP 230 ms / CLS 0.00 を達成するまでの全記録を実コード付きで解説します。
1. Before:Rustrak が突きつけた「Failed(スコア 70)」の実測値
@sentry/astro 経由で Rustrak に蓄積された本番 Web Vitals(p75)の初期計測値は次の通りでした。
| 指標 | Before(Rustrak p75) | 評価・内訳 |
|---|---|---|
| Web Vitals スコア | 70 | Failed |
| LCP | 3.50 s | Needs improvement(Poor 33%) |
| FCP | 5.72 s | Poor 60% |
| TTFB | 4.92 s | Poor 50% |
| INP | 16 ms | Good 100% |
| CLS | 0.00 | Good 100% |
INP(16 ms)と CLS(0.00)は 100% Good なのに、初期描画系(TTFB / FCP / LCP)だけが極端に悪化していました。しかも静的サイトで TTFB 4.92 s・FCP 5.72 s という異常値が出ていたため、Chrome DevTools の Performance トレース・Network パネル・レスポンスヘッダー・設定ファイルを総点検しました。
2. 原因調査で判明した 5 つのボトルネック
調査の結果、次の 5 つの問題が重なっていたことが判明しました。
| # | ボトルネック | 具体的な症状・実測値 | 主な影響 |
|---|---|---|---|
| 1 | レンダーブロッキング外部 CSS | 外部 CSS 2 本の取得待ちにより、LCP の Element render delay が 542 ms(LCP 全体の 54.8%) | FCP / LCP |
| 2 | Cloudflare Pages キャッシュ未設定 | public/_headers 未設定で全アセット・HTML が max-age=0 & cf-cache-status: DYNAMIC |
TTFB / 再訪 LCP |
| 3 | LCP 画像のプリロード不足・二重取得・過大サイズ | ヒーロー画像のプリロード不足、<video poster={image}> による .webp/.jpg の二重取得、最大 5955×3350px / 716 KB の過大画像 |
LCP |
| 4 | 初期ロードの帯域・CPU 競合 | GTM(289.6 KB)・CloudWatch RUM(225.3 KB)・ヒーロー動画(1.7 MB) が初期描画と同時に開始 | FCP / LCP |
| 5 | 計測ノイズ混入と Cloudflare 設定 | sentry.client.config.js の本番ドメイン制限漏れによるローカル/プレビュー値混入、Cloudflare Rocket Loader・Bot Challenge(cf_clearance) による TTFB 悪化 |
TTFB / FCP |
DevTools 上でも外部 CSS 2 本だけで LCP の半分以上を消費していたため、「描画ブロック解消・キャッシュ・アセット軽量化」と「計測の純化・Cloudflare 見直し」を並行して実施しました。
3. 最大のハマりどころ:inlineStylesheets: 'always' と PurgeCSS の競合
inlineStylesheets: 'always' とまず、LCP の 54.8%(542 ms)を占めていた外部 CSS 2 本のレンダリングブロック解消に着手しました。Astro 標準の build.inlineStylesheets: 'always' を有効にすれば 1 行で終わるはず——と試したところ、思わぬ罠にハマりました。
罠:未パージの Bulma CSS 全量が埋め込まれ HTML が 264 KB に膨張
build.inlineStylesheets: 'always' を有効にしてビルドした結果、dist/index.html は 264 KB(gzip 45.8 KB) まで膨れ上がりました。
原因は Astro 本体と astro-purgecss の実行順序 です。Astro 標準のインライン化が先に走り、Bulma CSS 全量(未使用ルール込み)が HTML の <style> へ展開されてしまいます。その後 astro:build:done で動く astro-purgecss は外部 .css ファイルを対象とするため、すでにインライン化された CSS をパージできなかったのです。
解決策:astro:build:done でパージ済み CSS のみをインライン化
build.inlineStylesheets はデフォルト(外部 CSS 出力)に戻して astro-purgecss に未使用 CSS を削らせたうえで、purgecss() の直後に実行される自前インテグレーション inlinePurgedStylesheets() を astro.config.mjs に実装しました。
// astro.config.mjs(抜粋)
import fs from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { defineConfig } from 'astro/config';
import purgecss from 'astro-purgecss';
function inlinePurgedStylesheets() {
return {
name: 'inline-purged-stylesheets',
hooks: {
'astro:build:done': async ({ dir }) => {
const outDir = fileURLToPath(dir);
const cssCache = new Map();
async function collectHtmlFiles(currentDir) {
const entries = await fs.readdir(currentDir, { withFileTypes: true });
const files = [];
for (const entry of entries) {
const fullPath = path.join(currentDir, entry.name);
if (entry.isDirectory()) {
files.push(...(await collectHtmlFiles(fullPath)));
} else if (entry.isFile() && entry.name.endsWith('.html')) {
files.push(fullPath);
}
}
return files;
}
const htmlFiles = await collectHtmlFiles(outDir);
const linkRegex = /<link\s+rel="stylesheet"\s+href="(\/_astro\/[^"]+\.css)"(?:\s*\/?)>/g;
for (const htmlFile of htmlFiles) {
const html = await fs.readFile(htmlFile, 'utf8');
const matches = [...html.matchAll(linkRegex)];
if (matches.length === 0) continue;
let updated = html;
for (const match of matches) {
const [fullTag, href] = match;
let css = cssCache.get(href);
if (css === undefined) {
const cssPath = path.join(outDir, href.replace(/^\/+/, ''));
try {
css = await fs.readFile(cssPath, 'utf8');
cssCache.set(href, css);
} catch {
cssCache.set(href, null);
css = null;
}
}
if (css !== null) {
const safeCss = css.replace(/<\/style>/gi, '<\\/style>');
updated = updated.replace(fullTag, `<style>${safeCss}</style>`);
}
}
if (updated !== html) {
await fs.writeFile(htmlFile, updated, 'utf8');
}
}
},
},
};
}
export default defineConfig({
integrations: [
// ...sentry, vue 等
purgecss({
safelist: {
standard: ['is-dark', 'is-active', 'is-copied', 'is-scrolled', 'is-menu-active'],
deep: [/^is-dark/, /^search-/, /^code-copy/, /^reading-progress/, /^heading-anchor/],
},
}),
inlinePurgedStylesheets(), // 必ず purgecss() の後ろに配置
],
});
| 方式 | dist/index.html(非圧縮) |
dist/index.html(gzip) |
外部 CSS リクエスト |
|---|---|---|---|
標準 inlineStylesheets: 'always'(未パージ) |
264 KB | 45.8 KB | 0 本 |
自前 inlinePurgedStylesheets()(パージ後) |
102 KB(-61%) | 24.6 KB(-46%) | 0 本 |
integrations 配列で purgecss() の直後に配置し、cssCache で共通 CSS の再読込を避けつつ </style> をエスケープすることで、102 KB(gzip 24.6 KB)・外部 CSS 0 本 を達成しました。
4. 残り 4 つのボトルネックを潰した改善実装
その他のボトルネックも順に解消しました(設定全体の構成は Astro×Cloudflare PagesのCWV・SEO最適化レシピ【実コード】 でも公開しています)。
4-1. public/_headers でエッジ・ブラウザキャッシュを設計
# public/_headers
/_astro/*
Cache-Control: public, max-age=31536000, immutable
/uploads/*
Cache-Control: public, max-age=2592000, stale-while-revalidate=86400
/img/*
Cache-Control: public, max-age=2592000, stale-while-revalidate=86400
/movie/*
Cache-Control: public, max-age=2592000, stale-while-revalidate=86400
/api/*
Cache-Control: no-store
/*
Cache-Control: public, max-age=0, must-revalidate
CDN-Cache-Control: public, max-age=3600
ハッシュ付きの /_astro/* は 1 年 immutable、/uploads/* などのメディアは 30 日+stale-while-revalidate=86400、HTML は CDN-Cache-Control: public, max-age=3600 でエッジキャッシュさせ、更新反映と TTFB 短縮を両立しました。
4-2. BaseLayout.astro の WebP 優先プリロードと data-cfasync="false"
data-cfasync="false"ビルド時に .webp の存在を判定し、LCP ヒーロー画像を <head> 最上部で fetchpriority="high" 付きプリロードします。また、ダークモード判定の初期インラインスクリプトには data-cfasync="false" を付与して Cloudflare 側のスクリプト書き換え対象から外しています。
---
// src/layouts/BaseLayout.astro(抜粋)
import fs from 'node:fs';
import path from 'node:path';
import { getWebpPath } from '../utils/categories';
const { preloadImage } = Astro.props;
let resolvedPreloadHref: string | undefined;
let resolvedPreloadType: string | undefined;
if (preloadImage) {
const webpCandidate = getWebpPath(preloadImage);
const hasWebp =
webpCandidate !== preloadImage &&
fs.existsSync(path.join(process.cwd(), 'public', webpCandidate.replace(/^\/+/, '')));
resolvedPreloadHref = hasWebp ? webpCandidate : preloadImage;
resolvedPreloadType = hasWebp ? 'image/webp' : undefined;
}
---
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
{resolvedPreloadHref && (
<link rel="preload" as="image" href={resolvedPreloadHref} type={resolvedPreloadType} fetchpriority="high" />
)}
<script is:inline data-cfasync="false">
// ダークモード判定などの初期インラインスクリプト
</script>
4-3. SiteHero.astro の二重取得解消と動画遅延
<video poster={image}> を削除して .webp / .jpg の二重取得を解消し、<img> に fetchpriority="high" と明示サイズを指定しました(初期改善では decoding="sync" で即座に描画する設定を適用し、レイアウト構造に合わせて最適化しています)。1.7 MB のヒーロー動画は preload="none" とし、load + requestIdleCallback 後に PC 幅のみ再生します。
<!-- src/components/SiteHero.astro(抜粋) -->
<picture class="hero-picture">
{hasWebp && <source type="image/webp" srcset={webpImage} />}
<img class="hero-bg" src={image} alt="" width="1600" height="900" fetchpriority="high" decoding="sync" />
</picture>
{home && (
<video class="hero-video" id="hero-video" muted loop playsinline preload="none" aria-hidden="true">
<source src="/movie/hero.mp4" type="video/mp4" />
</video>
)}
<script>
const startHeroVideo = () => {
const video = document.getElementById('hero-video') as HTMLVideoElement | null;
const prefersReduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
if (video && window.innerWidth > 768 && !prefersReduced) {
video.preload = 'metadata';
video.play().catch(() => {});
}
};
const scheduleHeroVideo = () => {
if ('requestIdleCallback' in window) {
window.requestIdleCallback(startHeroVideo, { timeout: 2000 });
} else {
window.setTimeout(startHeroVideo, 1000);
}
};
if (document.readyState === 'complete') scheduleHeroVideo();
else window.addEventListener('load', scheduleHeroVideo, { once: true });
</script>
4-4. GTM / CloudWatch RUM の遅延読み込みと過大画像 9 組の再圧縮
GTM(289.6 KB) と CloudWatch RUM(225.3 KB) も load + requestIdleCallback で初期表示後に退避しました(CloudWatch RUM は監視を Rustrak へ一本化する過程で整理済み)。
<!-- src/components/google_tag_manager_for_head.astro -->
<script is:inline data-cfasync="false">
(function () {
function loadGtm() {
(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var j=d.createElement(s),
dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;d.head.appendChild(j);
})(window,document,'script','dataLayer','GTM-XXXXXXX');
}
function schedule() {
if ('requestIdleCallback' in window) window.requestIdleCallback(loadGtm, { timeout: 3000 });
else window.setTimeout(loadGtm, 1500);
}
if (document.readyState === 'complete') schedule();
else window.addEventListener('load', schedule, { once: true });
})();
</script>
さらに、public/uploads/ 内の過大画像 9 組 を表示解像度へリサイズ+WebP 再圧縮し、最大 5955×3350px / 716 KB → 91 KB(約 87% 削減)、合計約 900 KB を削減しました。
4-5. sentry.client.config.js の本番ドメイン限定とノイズ除外
ローカル確認やプレビュー URL の計測値が本番 p75 に混ざるのを防ぐため、window.location.hostname で本番ドメインのみに限定し、Bot・バックグラウンドタブ・CWV 未計測の idleTimeout を除外しました。
// sentry.client.config.js(抜粋・DSN はマスク済み)
import * as Sentry from "@sentry/astro";
const BOT_USER_AGENT_PATTERN =
/bot|crawler|spider|headlesschrome|lighthouse|pagespeed|gptbot|claudebot|curl|wget/i;
function isAutomatedClient() {
if (typeof navigator === "undefined") return false;
if (navigator.webdriver) return true;
return BOT_USER_AGENT_PATTERN.test(navigator.userAgent || "");
}
const startedHidden =
typeof document !== "undefined" && document.visibilityState === "hidden";
Sentry.init({
dsn: "https://<YOUR_KEY>@rustrak.example.com/1",
enabled:
import.meta.env.PROD &&
typeof window !== "undefined" &&
window.location.hostname === "www.example.com" &&
!isAutomatedClient(),
environment: import.meta.env.MODE,
release: typeof __SENTRY_RELEASE__ !== "undefined" ? __SENTRY_RELEASE__ : undefined,
tracesSampleRate: 1.0,
beforeSendTransaction(event) {
const trace = event.contexts?.trace;
if (trace?.op === "pageload") {
if (startedHidden) return null;
const finishReason = trace.data?.["sentry.idle_span_finish_reason"];
const m = event.measurements || {};
if (finishReason === "idleTimeout" && m.lcp === undefined && m.cls === undefined && m.inp === undefined) {
return null;
}
}
return event;
},
enableLogs: true,
integrations: [
Sentry.browserTracingIntegration({ enableInp: true }),
Sentry.browserSessionIntegration(),
Sentry.consoleLoggingIntegration({ levels: ["warn", "error"] }),
],
});
5. Cloudflare 側の必須チェック項目(TTFB を壊す 2 つの設定)
コード最適化とあわせて、TTFB 4.92 s の要因になりやすい Cloudflare ダッシュボード設定も必ず点検します。
- Rocket Loader を OFF(Speed → Optimization → Content Optimization): 全スクリプトを独自ローダー経由に書き換えるため、最適化済みの Astro サイトでは初期描画の遅延や計測タイミングずれの原因になります。
- Managed Challenge / Bot Fight Mode の確認(Security → Bots / WAF): 初回訪問で
cf_clearance発行の検証画面が挟まると TTFB が数秒単位で悪化します。Security Events で一般ユーザーへの過剰なチャレンジが出ていないか確認します。
6. After:Chrome DevTools トレース実測と改善結果
全施策の適用後、Chrome DevTools の Performance トレースでデスクトップおよびモバイル(390×844 / Fast 3G / CPU 4x)を実測した結果です。
| 計測環境・項目 | Before | After | 改善ポイント |
|---|---|---|---|
| デスクトップ LCP | 3.50 s(Rustrak p75) | 156 ms | 外部 CSS 0 本+WebP プリロード+エッジキャッシュ |
| LCP Element render delay | 542 ms(LCP の 54.8%) | 128 ms(-76%) | inlinePurgedStylesheets() でブロッキング解消 |
| モバイル LCP(390×844 / Fast 3G / CPU 4x) | 3.50 s(p75 基準) | 230 ms | 画像 9 組圧縮(716 KB→91 KB 等)+動画・JS 遅延 |
| CLS(デスクトップ / モバイル) | 0.00 | 0.00 | 画像サイズ明示と初期スタイル固定を維持 |
dist/index.html サイズ |
264 KB(標準 inline 試行時) | 102 KB(gzip 24.6 KB) | PurgeCSS 後インライン展開で 61% 削減 |
ネットワークと CPU を絞った モバイル Fast 3G / CPU 4x 条件でも LCP 230 ms・CLS 0.00 まで短縮できました。今後は __SENTRY_RELEASE__(Git コミット SHA)単位で Rustrak の推移を追い、異常が出ればシリーズ第 2 回の Rustrak MCP×AIエージェントで本番エラー調査を自動化【実践】 のワークフローで即座に原因を特定できます。
まとめ
ラボ計測の良好なスコアだけでは、本番の実ユーザー体験(RUM)に潜むキャッシュ漏れや Cloudflare 設定・計測ノイズまでは見抜けません。
- 検知:Rustrak の Web Vitals 計測で「Failed(スコア 70)・LCP 3.50 s / TTFB 4.92 s」を可視化できた
- 突破:
build.inlineStylesheets: 'always'とastro-purgecssの競合を、astro:build:doneのinlinePurgedStylesheets()で解決した(264 KB → 102 KB) - 総仕上げ:
_headers・WebP プリロード・画像再圧縮・動画 / GTM / RUM 遅延・本番ドメイン限定・Cloudflare 見直しにより、デスクトップ LCP 156 ms・モバイル Fast 3G LCP 230 ms を実現した
全 3 回の 「Rustrak 軽量セルフホスト監視シリーズ」 はこれにて完結です。ぜひ監視基盤の構築から継続的なパフォーマンス改善まで実践してみてください。
シリーズ記事・関連記事
- シリーズ第 1 回:Rustrak×Astroで軽量セルフホスト監視|Sentry代替構築ガイド
- シリーズ第 2 回:Rustrak MCP×AIエージェントで本番エラー調査を自動化【実践】
- 関連記事(CWV・SEO 最適化):Astro×Cloudflare PagesのCWV・SEO最適化レシピ【実コード】
Diverstage では、Astro × Cloudflare Pages による高速な Web サイト制作・Core Web Vitals 改善から、Rustrak を活用した省コストな本番監視・パフォーマンス継続運用まで一貫してご支援しています。
「自社サイトの Core Web Vitals 悪化原因を特定したい」「実ユーザー計測を導入して改善サイクルを回したい」という方は、下記よりお気軽にご相談ください。




