この解答例はChatGPTによって生成されています,正しいかは自己判断で。 皆の投稿からも解答例が見つかるかもしれませんよ。
BFE.devでのAI解答例 - フロントエンド面接質問
71. 画像の lazy loadはどう実装する?
自分で実装する場合は、以下の手順に従って実装することができます。
-
画像要素(
<img>
タグなど)にloading="lazy"
属性を追加する。例:
<img src="image.jpg" loading="lazy" alt="example image">
-
JavaScriptを使用して、画面外にある画像を検出するようにします。
例:
const images = document.querySelectorAll('img[loading="lazy"]');const options = { rootMargin: '0px', threshold: 0.1};const imageObserver = new IntersectionObserver((entries, observer) => { entries.forEach(entry => { if (entry.isIntersecting) { const lazyImage = entry.target; lazyImage.src = lazyImage.dataset.src; lazyImage.classList.remove('lazy'); imageObserver.unobserve(lazyImage); } });}, options);images.forEach(image => { imageObserver.observe(image);});
上記の例では、
IntersectionObserver
API を使用して、画面外にある画像と何回交差したかを検出します。交差した場合、画像要素のsrc
属性を更新し、lazy
クラス名を取り除いて画像を表示します。必要に応じて、適切なローディング画像も使用することができます。