0
0

More than 3 years have passed since last update.

Lighthouse対応でimageタグ利用時の注意点

Last updated at Posted at 2021-07-01

前提

レスポンシブ対応してるサイト

最近サイトのLighthouse対応で、画像周りにいくつかの注意点があり、そちらをまとめてみました。

altがない

<%= image_tag "sample.png", alt: 'sample image' %>

Defer offscreen images

ファーストビューではない画像はloading lazyをつけて、スクロールして表示したら、画像をロードする

<%= image_tag "sample.png", alt: 'sample image', loading: 'lazy' %>

Image elements do not have explicit width and height

画像のwidthとheightは設定して、画像がロードされるまで領域を取る

<%= image_tag "sample.png", alt: 'sample image', loading: 'lazy', width: 100, height: 100 %>

Properly size images

実際の画像サイズは表示してる枠の画像サイズより4KB以上大きい場合は警告される

例えば、表示幅30pxの枠で300x200の画像を表示するとエラーになる

この場合は表示してる枠と合わせて、幅30pxの画像を用意した方が良い

Retina対応

解像度が高いデバイス増えており、2xの画像を用意して、srcsetかpicture tagで対応

<%= image_tag "sample.png", alt: 'sample image', loading: 'lazy', width: 100, height: 100, srcset: 'sample.png 1x, sample@2x.png 2x' %>

最近3xのスマホも出てきて、今後3xの画像も対応した方が良いかもしれないです

PCとスマホで表示する画像のアスペクト比が違う場合

pictureタグはアスペクト比が違う場合は、CLSの問題あり、現状は使えないようです。

画像名  高さ
sample_pc.png 1200 300
sample_sp.png 300 300

この場合はpictureにすると、PCの表示がおかしくなる可能性がある

<picture>
  <%= tag :source, { media: '(min-width: 769px)', srcset: image_url('sample_pc.png') } %>
  <%= image_tag 'sample_sp.png', width: 300, height: 300 %>
</picture>

あまり良い方法が見つからなくて、CSSのmedia queryで切替する

<%= image_tag 'sample_pc.png', class: 'pc-image', width: 1200, height: 300 %>
<%= image_tag 'sample_sp.png', class: 'sp-image', width: 300, height: 300 %>
0
0
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
0
0