yall.js で画像やリソースの遅延読み込みを行う

aync が広がる優しい世界


Posted on Sun, Jan 13, 2019
Tags javascript, yall.js, web

<img>, <picture>, <video>, <iframe> を遅延読み込みする yall.js

lighthouse を参考に webpage を高速化していく – Think Abstract を行っている最中、Google の技術記事を読んでいたら、malchata/yall.js というのを知った。

これを利用すると web page の最初の読み込みでダウンロードされる画像を少なくできるため、非常に快適に page を見ることができる。

また、あわせて画面のサイズにあわせてイメージのサイズがかわるように下記の Hugo の shortcodes を作成した。

参考:Responsive Images in Hugo | Adam Wills

/layouts/shortcodes/img.html

<div class="picture">
  {{ if .Get "caption"}}
  <figure>
  {{ end }}
    <picture>
      <img class="lazy post-img" data-src="{{ .Get "src" }}.{{ .Get "type" }}" alt="{{ .Get "alt" }}" style="{{ .Get "style" }}">
    </picture>
  {{ if .Get "caption"}}
    <figcaption>{{ .Get "caption" }}</figcaption>
  </figure>
  {{ end }}
</div>

img の class に lazy と、data-src が指定されているのがポイント。

post-img の css には、max-width: 100% を指定することで、画面のサイズに追従させた。

あとは、

{{< img src="/assets/2019/01/lighthouse_google_mobile" type="png" >}}

と markdown 内で呼び出せば、遅延読み込みし、かつ画面のサイズにあったイメージが作成される。

Hugo はまだまだ使いこなせるし、最適化しがいがあるなぁ。yall.js を使うと下記のような形になった。


ちなみに、How To Escape Shortcode In Hugo Template | Lua Software Code より、

{{</* ... */>}}

で shortcode はエスケープできるようだ。奥が深い…