Webページの表示速度をあげるためにページの軽量化を行います。軽量化する対象としては下記が挙げられるが、今回はHTMLファイルに注目してみます。
・html
・javascript
・css
※htmlファイルの軽量化では明らかな速度改善は中々見られませんが、
パフォーマンスを重視している場合などは良いと思います。
1.使用ツール
今回はGoogleが提供している「HTMLMinifier」というものを使用します。
2.導入手順
ツールの利用にNode.jsが必要になってくるのでインストールします。
ツールをインストールします。
npm install html-minifier -g
3.実行
下記コマンドで実行します。
html-minifier --collapse-whitespace --remove-comments --remove-optional-tags --remove-redundant-attributes --remove-script-type-attributes --remove-tag-whitespace --use-short-doctype --minify-css true --minify-js true ECMAScript.html -o ECMAScript_minify.html
4.実験
ファイルサイズの大きい「ECMAScript」のページで実験してみます。
https://kangax.github.io/compat-table/es6/
表1. ファイルサイズ比較
ファイルサイズ(適用前) | ファイルサイズ(適用後) |
---|---|
5.79 MB | 6.43 MB |
表2. DOMContentLoadedのパフォーマンス計測
1 | 2 | 3 | 4 | 5 | 平均 |
---|---|---|---|---|---|
2.53 | 2.51 | 2.44 | 2.49 | 2.41 | 2.47 |
2.78 | 3.09 | 2.81 | 2.81 | 2.87 | 2.87 |
5.結果
あまり早くなったわけではありません、
コンテンツが多くなりファイルサイズが大きくなったものに
のみ適用とかでいいと思います。
6.おまけ
フォルダ内のすべてのhtmlファイルを軽量化するコマンドです。
@echo off rem htmlファイルを一つずつ%%aに代入してループを回す setlocal enabledelayedexpansion for %%a in (*.html) do ( set fname=%%a call html-minifier ^ --collapse-whitespace --remove-comments --remove-optional-tags ^ --remove-redundant-attributes --remove-script-type-attributes ^ --remove-tag-whitespace --use-short-doctype --minify-css true --minify-js true ^ !fname! -o !fname:.=_minify.! )