目的

サイトを高速化して検索ランキングを改善してサイトへの流入を増やす。

以下記事でGoogleは表示速度をモバイル検索ランキングの指標とすることに言及している。
ref. https://webmaster-ja.googleblog.com/2018/01/using-page-speed-in-mobile-search.html

参考文献

  • 書籍
    • 久保田 光則 Webフロントエンド ハイパフォーマンス チューニング 技術評論社
    • 佐藤 歩,泉水 翔吾. 超速! Webページ速度改善ガイド ── 使いやすさは「速さ」から始まる (WEB+DB PRESS plus) (Japanese Edition)
  • レンダリング処理
    • https://developers.google.com/web/fundamentals/performance/critical-rendering-path/constructing-the-object-model?hl=ja
    • https://developers.google.com/web/fundamentals/performance/critical-rendering-path/render-tree-construction?hl=ja
    • https://developers.google.com/web/fundamentals/performance/critical-rendering-path/render-blocking-css?hl=ja
    • https://developers.google.com/web/fundamentals/performance/critical-rendering-path/adding-interactivity-with-javascript?hl=ja
    • https://developers.google.com/web/fundamentals/performance/critical-rendering-path/optimizing-critical-rendering-path?hl=ja
    • https://developers.google.com/web/fundamentals/performance/critical-rendering-path/page-speed-rules-and-recommendations?hl=ja
  • DevTools
    • https://developers.google.com/web/tools?hl=en
    • https://developers.google.com/web/tools/chrome-devtools/?hl=en
    • https://developers.google.com/web/tools/chrome-devtools/evaluate-performance/timeline-tool?hl=ja
  • web.devcss
    • https://web.dev/
  • Google
    • https://webmaster-ja.googleblog.com/2020/06/evaluating-page-experience.html
    • https://support.google.com/webmasters/answer/9205520?ref_topic=7440006#about_data
    • https://developers-jp.googleblog.com/2020/05/web-vitals.html
    • https://webmasters.googleblog.com/2018/01/using-page-speed-in-mobile-search.html
  • Others
    • https://developers.google.com/web/updates/2018/09/inside-browser-part1

HTTP/1.1 TCP同時接続数

単一のドメインに対するTCPの同時接続数は、多くのブラウザで最大6に制限されていて、HTTP/1.1ではその制限の中で複数のTCPコネクションを持つことで並行性を確保しています(

佐藤 歩,泉水 翔吾. 超速! Webページ速度改善ガイド ── 使いやすさは「速さ」から始まる (WEB+DB PRESS plus) (Japanese Edition) (Kindle の位置No.1297-1299). Kindle 版.

TCP同時接続数は規定では2だが、現状多くのブラウザのTCP同時接続数は6となっている。
TCP同時接続が6なので、サブリソース(CSS/JavaScript/画像)のリクエスト数やファイルサイズを最適化する必要がある。

フレームワーク - Lighthouse/PageSpeed Insights -

Googleは、ページのパフォーマンスを評価するフレームワークLighthouseを公開している。
Lighthouseを手軽に使用するツールとして以下の2つがある1。 (ツールによって指標の呼び方が異なる)

ツール DevTools Lighthouse PageSpeed Insight
指標 Performance > Metrix ラボデータ

Ref.

指標(評価システム) - Metrics/ラボデータ(2020/07/23現在)-

  • https://web.dev/metrics/
  • https://simulate.site/cheatspeed-insights/
項目 内容 対策
First Contentful Paint(FCP)
https://web.dev/fcp/
最初のコンテンツが描画されるまでの時間1。
The First Contentful Paint (FCP) metric measures the time from when the page starts loading to when any part of the page’s content is rendered on the screen. For this metric, “content” refers to text, images (including background images), elements, or non-white elements.</q>[^2]
クリティカルレンダリングパス高速化
Largest Conetntful Paint(LCP)
https://web.dev/lcp/
最大コンテンツの描画
ビューポート(=ファーストビュー)で最も大きな領域を占めるテキスト要素または画像要素を描画するまでの時間。
The Largest Contentful Paint (LCP) metric reports the render time of the largest image or text block visible within the viewport.
First Contentful Paintを改善
Largestコンテンツ(メイン画像等)を最適化
Speed Index(SI)
https://web.dev/speed-index/
https://sites.google.com/a/webpagetest.org/docs/using-webpagetest/metrics/speed-index
速度インデックス
ページロード中にいかに速く描画が進行するか。
Speed Index measures how quickly content is visually displayed during page load. Lighthouse first captures a video of the page loading in the browser and computes the visual progression between frames. Lighthouse then uses the Speedline Node.js module to generate the Speed Index score.
First Contentful Paintを改善
Largestコンテンツ及びファーストビューのコンテンツを改善
Time To Intractive(TTI)
https://web.dev/tti/
インタラクティブになるまでの時間
条件1:FCPを開始してからメインスレッドに5秒以上の余裕が生じた時点からさかのぼって、最後のロングタスク(50ms以上のタスク)の終わり
条件2:TCPコネクションが2以下
FCPの後に取得するリソース数およびロングタスクを改善
Total Blocking Time(TBT)
https://web.dev/tbt/
合計ブロック時間(JavaScriptの負荷)
FCPとTTI間のロングタスク(50ms以上タスク)合計時間。The Total Blocking Time (TBT) metric measures the total amount of time between First Contentful Paint (FCP) and Time to Interactive (TTI) where the main thread was blocked for long enough to prevent input responsiveness.
TTIが短ければ相対的にTBTも短くなる。
ロングタスクを改善
Cumulative Layout Shift(CLS)
https://web.dev/cls/
累積レイアウト変更(誤操作の誘引)
CLS measures the sum total of all individual layout shift scores for every unexpected layout shift that occurs during the entire lifespan of the page.
レイアウトの段階的な変化と影響を受ける領域の大きさ。画像の読み込み完了やJavaScriptにより後からの要素が挿入されレイアウトがズレる事象が典型例。ちなみにスピードとは無関係。
JavaScriptによる要素操作を改善
画像サイズ指定漏れ改善

ref. https://github.com/GoogleChrome/lighthouse/blob/d2ec9ffbb21de9ad1a0f86ed24575eda32c796f0/docs/scoring.md#how-are-the-scores-weighted

クリティカルレンダリングパス

クリティカルレンダリングパスとは

ページは、Loading -> Scripting -> Rendering -> Paintingを経て表示される。この処理をクリティカルレンダリングパスと呼ぶ(フレームともいう)。

  1. Loading
    1. リソースのロード(Load)
    2. 解析(Parse) Parseにはdocument.write()といったJavaScriptの解析も含む
      • DOMツリー構築
      • CSSOM(CSS Object Model)ツリー構築
  2. Scripting
  3. Rendering:LoadingとScriptingで作成されたDOMツリーとCSSOMツリーをもとにして、スタイル計算とレイアウト処理を行ってレンダリングツリー(StyleTreeともいう)を構築
    1. スタイル計算(Calculate Style)
    2. レイアウト処理(Layout)
  4. Paint:レンダリングツリーをもとに実際にブラウザに描画
    1. Paint:2次元描画命令発行
    2. Rasterize:Paintで発行された命令を元にピクセルを作成(≒レイヤーを作成)
    3. Composite Layouts:すべてのレイヤーを処理

Webサイト高速化作業の1つが、上記クリティカルレンダリングパスの高速化である。

ref. Webフロントエンド ハイパフォーマンス チューニング 久保田 光則 ref. https://developers.google.com/web/fundamentals/performance/critical-rendering-path?hl=ja

クリティカルレンダリングパスをブロックする処理

CSSとJavaScriptのロード中は、DOMツリーやCSSOMツリーに影響を与える可能性があるためレンダリング処理をブロックします。

佐藤 歩,泉水 翔吾. 超速! Webページ速度改善ガイド ── 使いやすさは「速さ」から始まる (WEB+DB PRESS plus) (Japanese Edition) (Kindle の位置No.1426-1427). Kindle 版.

JavaScriptによるクリティカルレンダリングパスのブロック

以下リンクは、JavaScriptの動作をわかりやすく解説している。
当文章のJavaScript部分は基本的に以下リンク先を引用したもの。

  • https://developers.google.com/web/fundamentals/performance/critical-rendering-path/adding-interactivity-with-javascript?hl=ja
  • https://developers.google.com/web/fundamentals/performance/critical-rendering-path/analyzing-crp?hl=ja

前提

  • JavaScript は非同期(async, defer)であると明示的に宣言されていない場合、DOM構築をブロック
  • 外部CSSも含めてCSSはDOMツリー構築をブロックしない
  • JavaScript は、DOM と CSSOM に対するクエリ(問い合わせ)と変更が可能なために、CSSOM構築(CSSダウンロード&パース)まで待機(よってDOM構築もその間ブロック)

※ 外部CSSも含めてCSSはDOMツリー構築をブロックしないが、JavaScriptが現れた時点で、CSSにアクセスする可能性が発生するので、記載位置より前にあるCSSをすべてロードするまでDOM構築はブロックされる。

詳細

  1. HTMLパーサーがscriptタグを検知
  2. DOM構築のプロセスを一時中断して、JavaScript エンジンに制御を渡す
  3. JavaScriptはCSSOM構築(CSSダウンロードとパース)が完了するまで待機
  4. JavaScriptエンジンがスクリプトを実行
  5. 実行が完了すると、ブラウザは中断前の位置に戻り、そこから DOM 構築を再開

レンダリングに関するイベント

DOMContentLoaded

DOMContentLoadedイベントは、ブラウザによるHTMLドキュメントのロード完了を示し、その他サブリソースのロードは保証しません。しかし

佐藤 歩,泉水 翔吾. 超速! Webページ速度改善ガイド ── 使いやすさは「速さ」から始まる (WEB+DB PRESS plus) (Japanese Edition) (Kindle の位置No.2268-2276). Kindle 版.

domContentLoaded: DOM の準備が整い、JavaScript の実行をブロックするスタイルシートが存在しなくなった時点を示します。つまり、これ以降、レンダリング ツリーの構築を開始できます。 多くの JavaScript フレームワークでは、このイベントを待ったうえで、それ自体のロジックの実行を開始します。このため、ブラウザでは、EventStart と EventEnd のタイムスタンプをキャプチャすることで、この処理の所要時間をトラッキングできるようにしています。

https://developers.google.com/web/fundamentals/performance/critical-rendering-path/measure-crp?hl=ja

load

DOMContentLoadedイベントはDOMツリーの構築完了を、loadイベントはDOMツリーに起因するサブリソースの取得および評価の完了を意味します。

佐藤 歩,泉水 翔吾. 超速! Webページ速度改善ガイド ── 使いやすさは「速さ」から始まる (WEB+DB PRESS plus) (Japanese Edition) (Kindle の位置No.1502-1503). Kindle 版.

クリティカルレンダリングパス高速化

以下のリンク内容を実行
https://developers.google.com/web/fundamentals/performance/critical-rendering-path/optimizing-critical-rendering-path?hl=ja

改善の基本

  1. サイズの大きいリソースの調査と改善(データの転送量をなるべく小さくすること)
    • サイズが大きいファイルはダウンロードに時間がかかる
    • HTTP/1.1においては同時接続数の1つを占有
    • 他リソースのダウンロードを阻害
    • 画像最適化
    • HTML/CSS/JavaScriptを最小化(Minify)
  2. リクエスト数の調査と改善(データの転送回数をなるべく少なくすること)
    • リソース(ファイル)を結合
    • 不必要なリソースの削除
    • 画像の遅延ロード
    • キャッシュを使用
  3. 待機時間が長いリクエストの調査と改善(データの転送距離をなるべく短くすること)
    • キャッシュを利用
    • CDNを利用

佐藤 歩,泉水 翔吾. 超速! Webページ速度改善ガイド ── 使いやすさは「速さ」から始まる (WEB+DB PRESS plus) (Japanese Edition) (Kindle の位置No.2070). Kindle 版.

改善リスト

  • JS/CSS/画像を結合(HTTP1.1が前提)
    • 同時接続数への改善
    • TCPハンドシェイクへの対策
  • HTML/JS/CSSを最小化(Minify)
  • 画像を最適化
    • ImageOptimaによる最適化
    • 動画形式WebPを導入 次世代フォーマットでの画像の配信
    • デバイスごとに最適な画像を配信(pictureタグ)
  • JS非同期読込(外部CSSdefer/async属性)
  • CSS遅延読込
  • 画像遅延読込
    • Google Chromeのloading="lazy"
  • ファーストビューのCSSをインライン化
  • web fontのpreload

最小化

サーバからブラウザに送信するリソースは、できる限り小さくするのが基本です。ダウンロードに時間がかかっているリソースに圧縮が適用されているかを確認しましょう。

佐藤 歩,泉水 翔吾. 超速! Webページ速度改善ガイド ── 使いやすさは「速さ」から始まる (WEB+DB PRESS plus) (Japanese Edition) (Kindle の位置No.1981-1983). Kindle 版.

  • htmlminifier:https://github.com/kangax/htmlminifier
  • cleancss:https://github.com/jakubpawlowicz/cleancss
  • cssnano:https://github.com/beneb/cssnano ※ 一番使用率が高いので、特別な理由がない限り使用
  • csso:https://github.com/css/csso
  • uglifyes:https://github.com/mishoo/UglifyJS2
  • ClosureCompiler:https://github.com/google/closurecompiler
  • SVGO:https://github.com/svg/svgo

佐藤 歩,泉水 翔吾. 超速! Webページ速度改善ガイド ── 使いやすさは「速さ」から始まる (WEB+DB PRESS plus) (Japanese Edition) (Kindle の位置No.1989-1997). Kindle 版.

Webp使用

  1. webpへ変換
  2. .htaccessを使って画像リクエストに対してwebpを返す
    • https://blog.ideamans.com/2019/02/webphtaccess.html

ディレクトリ内画像をexample.jpg -> example.jpg.webpに一括変換。

$ for file in *; do cwebp "$file" -o "${file%}.webp"; done

web fontのpreloadとページ速度改善

  • web fontのpreloadとページ速度改善

  • フォント形式には色々あるがWebでは使用する形式はwoff, woff2

    http://www.yabi-blog.xyz/font_ttf_otf_woff/

  • 本体ファイル(例:font-awesome.css)のsrcプロパティで読み込むが事前にpreloadしておけば2回読み込むことはない

web fontファイルは、preloadしない場合は呼び出しもとがダウンロードされて、フォントが適用(解釈)されるときに、逐次的にロードされる。 (逆に言えば、フォントが利用されていなければフォントファイルはロードされない)

使用されることがわかっている場合は、preloadすることによって呼び出し元と並列でロードできる可能性が高まる。

例) 同一ドメインにwoff/woff2が配置されていてもcrossoriginを設定しないと正常に動作しない。

<link rel='preload' as='font' type='font/woff2' crossorigin id='font-awesome-woff2-css'  href='http://localhost:8080/wp-content/themes/kanagata/css/libs/fonts/fontawesome-webfont.woff2?ver=4.3.0'   />
<link rel='preload' as='font' type='font/woff' crossorigin id='font-awesome-woff-css'  href='http://localhost:8080/wp-content/themes/kanagata/css/libs/fonts/fontawesome-webfont.woff?ver=4.3.0'   />
<link rel='stylesheet' id='font-awesome-css'  href='http://localhost:8080/wp-content/themes/kanagata/css/libs/font-awesome/font-awesome.min.css?ver=4.3.0' type='text/css' media='all' />

CDN

  • https://developers.google.com/speed/libraries
  • https://www.cloudflare.com/ja-jp/

キャッシュ

ブラウザキャッシュ

ブラウザキャッシュはすでにキャッシュされたのもをサーバー側で強制的にクリアすることはできない。 次回から無効かしかできない。

やるとしたら以下が可能な場合のみ

対象MIMEタイプの全ファイルにデプロイ時にプレフィックスを付与できる場合。

例)スタイルとしてbootstrap.min.cssとstyle.min.cssしかなくデプロイ時に以下のようなサフィックスを付与可能な環境

  • bootstrap.min.css?
  • style.min.css?
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/x-icon "access plus 6 months"
ExpiresByType text/css "access plus 1 months"
</IfModule>

ref. https://lpeg.info/html/htaccess_cache.html

現実的には採用は難しい。 faviconは可能化も?

Web Vitals

https://web.dev/vitals/ https://web.dev/defining-core-web-vitals-thresholds/

Cumulative Layout Shift(CLS)の改善

https://web.dev/optimize-cls/

Chrome DevTools

Disable Cache

Performanceタブでキャッシュを使用しない(推奨)設定にする場合もNetworkタブのDisable Cacheをチェック。

DOMContentLoaded/First Paint/load

フレーム チャートには 1~3 本の点線が縦に表示されることがあります。青い線は DOMContentLoaded イベントを表します。 緑の線は最初のペイントまでの時間を表します。 赤い線は load イベントを表します。

https://tech.mercari.com/entry/2018/12/12/090156

Networkタブ

概要欄には transferred と resources の 2種類のサイズが記載されています。transferred は圧縮されたサイズで、resources は非圧縮のサイズです。

https://murashun.jp/blog/20190912-01.html

  • https://qiita.com/nanakenashi/items/463e66ae44d15b55d882

PerformanceタブのメインチャートNetwork

意味については以下サイトが詳しい
https://engineering.mercari.com/blog/entry/2018-12-12-090156/

備考

用語

  • ネットワーク ラウンドトリップ

通信やネットワーク、データ伝送などの分野では、通信相手に信号やデータを発信して、応答が帰ってくるまでの過程をラウンドトリップという。この過程にかかる時間のことを「ラウンドトリップタイム」(RTT:Round-Trip Time)「ラウンドトリップ遅延」(RTD:Round-Trip Delay)などという。

http://e-words.jp/w/%E3%83%A9%E3%82%A6%E3%83%B3%E3%83%89%E3%83%88%E3%83%AA%E3%83%83%E3%83%97.html#:~:text=%E9%80%9A%E4%BF%A1%E3%82%84%E3%83%8D%E3%83%83%E3%83%88%E3%83%AF%E3%83%BC%E3%82%AF%E3%80%81%E3%83%87%E3%83%BC%E3%82%BF%E4%BC%9D%E9%80%81,%2DTrip%20Delay%EF%BC%89%E3%81%AA%E3%81%A9%E3%81%A8%E3%81%84%E3%81%86%E3%80%82

Performanceの色

CPU

  • 青色 (Loading): HTTPリクエストやHTMLのパース処理
  • 黄色 (Scripting): JavaScriptで行われた処理全般
  • 紫色 (Rendering): スタイルの評価やレイアウト算出
  • 緑色 (Painting): ペイント処理や画像のラスタライズ(ビットマップ化)
  • 灰色 (Other): その他

    https://tech.mercari.com/entry/2018/12/12/090156

Network

  • 青色: HTML
  • 紫色: CSS
  • 緑色: 画像
  • 黄色: JavaScript
  • 灰色: フォント

    https://tech.mercari.com/entry/2018/12/12/090156

Main(メインスレッド)

CPUと同じ。

ツール

評価

  • Lighthouse(Chrome DevTools)
  • PageSpeed Insights:https://developers.google.com/speed/pagespeed/insights/?hl=ja
  • Search Console モバイル フレンドリー テスト:https://search.google.com/test/mobile-friendly?hl=JA
  • Think with Google:https://www.thinkwithgoogle.com/intl/ja-jp/feature/testmysite/
  • WebPageTest:https://www.webpagetest.org/

画像最適化ツール

  • ImageOptim:https://imageoptim.com/howto.html
  • WepP
    • https://squoosh.app/ オンライン
    • https://developers.google.com/speed/webp/docs/cwebp コマンドライン brewでインストール
  • WordPressプラグイン
    • https://wordpress.org/plugins/search/convert+webp/
      • EWWW Image Optimizer

その他

  • Web Vital(Chrome拡張): https://chrome.google.com/webstore/detail/web-vitals/ahfhijdlegdabablpippeagghigmibma

.htaceess

  • http://httpd.apache.org/docs/2.4/mod/mod_rewrite.html
    公式
  • https://weblabo.oscasierra.net/apache-rewritecond-base/ 日本語での仕様解説
  • https://www.findxfine.com/programming/wp/995553772.html
  • https://blog.ideamans.com/2019/02/webphtaccess.html
  • https://colo-ri.jp/develop/2010/04/mod_rewriterequest_filenamescript_filename.html
  1. コンテンツとは For this metric, “content” refers to text, images (including background images), elements, or non-white elements.</q> ↩ ↩2