LoginSignup
5
3

More than 5 years have passed since last update.

Material Icon Font で必要なアイコンだけ読み込む

Posted at

<link href="https://fonts.googleapis.com/icon?family=Material+Icons"
      rel="stylesheet">

この CSS の URL は Google Fonts の text パラメータ に対応しているので、

<link href="https://fonts.googleapis.com/icon?family=Material+Icons&text=face"
      rel="stylesheet">

こう書くと <i class="material-icons">face</i> だけに対応したフォントファイルが読み込まれる。
……が、このやり方だと、例えば下記のように書くと

<link href="https://fonts.googleapis.com/icon?family=Material+Icons&text=block"
      rel="stylesheet">

block と lock 、 2 つのアイコンが読み込まれてしまい、ちょっと容量が増える。
しかもこれ、 text=kcolb とか書いても、 block と lock が有効になる。つまり、使うアイコンが増えてきて、ほぼ a-z 指定してる状況になると、全部のアイコン読み込んでるのと結局変わらん話になる。

そこで、コードポイントの方で指定することを考える。
face アイコンのコードポイントは E87C なので、 encodeURI('\uE87C') で UTF-8 エンコードした結果を text パラメータに渡してやる。

<link href="https://fonts.googleapis.com/icon?family=Material+Icons&text=%EE%A1%BC"
      rel="stylesheet">

これで <i class="material-icons">&#xE87C;</i> (face アイコン) のみが有効になるのだが、こちらのやり方だとリガチャでの指定 (face という文字列での指定) はできない。

まとめ

  • 全部読み込んでも 50kB いかないので、 semantics のほうが大事よって人は全部読み込んだほうが楽
  • 容量をちょっとでも減らしたいならコードポイントで指定して削ることができる
5
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3