Daily Code / 60

画像が読み込まれた瞬間のレイアウト移動を探す|PerformanceObserver

画像が後から現れると、読んでいた本文が急に下へ動くことがあります。

画像の領域を予約し、移動量を予約なしの場合と比べます。

ライブデモへ

最初に知っておく用語

レイアウトシフト
表示済みの要素が意図せず移動すること
PerformanceObserver
ブラウザーの性能記録を受け取る仕組み

XYチャートで考える

立ち上がる線は予約なしです。

水平な線は予約ありです。

この図は測定結果を予告する例で、実測値はライブデモで確かめます。

Mermaidのソースを見る
xychart-beta
    title "画像の高さが180pxの場合の説明例"
    x-axis ["読込前", "読込後"]
    y-axis "本文の位置(相対値 px)" 0 --> 200
    line [0, 180]
    line [180, 180]

ライブデモ

公開データや検証用のファイルで試してください。

予約なし、予約ありの順に試す。

本文の位置を見比べる。


実装コード
()=>{let cancel=()=>{};const h=panel();const sample=reserved=>{cancel();h.replaceChildren();const events=[];let observer;const can=PerformanceObserver.supportedEntryTypes?.includes('layout-shift');if(can){observer=new PerformanceObserver(l=>{for(const e of l.getEntries())events.push({時刻:Math.round(e.startTime),移動値:e.value,直近入力:e.hadRecentInput});say({本文の移動px:p.offsetTop-start,記録:events})});observer.observe({type:'layout-shift'})}const i=el('img',h);i.alt='遅れて表示する画像';if(reserved){i.width=480;i.height=180;i.style.aspectRatio='8/3';i.style.display='block'}else{i.style.display='none'}const p=el('p',h,'この本文の位置を観察します。'),start=p.offsetTop;const t=setTimeout(()=>{i.onload=()=>say({本文の移動px:p.offsetTop-start,記録:can?events:'この環境は layout-shift 非対応'});i.style.display='block';i.src=svg(480,180,'Daily Code')},850);cancel=()=>{clearTimeout(t);observer?.disconnect()}};button('予約なし',()=>sample(false));button('予約あり',()=>sample(true));cleanup=()=>cancel()}

結果の見方

予約ありでは画像が現れても本文の位置が変わりにくい。

計測値に加えて本文の移動ピクセル数も表示する。

クリック直後の移動は、ページ全体の指標を集計する際に扱いが異なることがある。

コードの要点

layout-shiftの対応を確認して記録し、移動値と発生時刻を比較する。

仕事で使うとき

画像に幅と高さを指定する。

測定値が出ない環境では位置の差も確認する。