How to Implement Lazy Loading Images with Claude Code
Learn how to implement lazy loading images using Claude Code. Includes practical code examples and step-by-step guidance.
画像遅延読み込みの重要性
Webページの読み込み速度に最も影響するのは画像です。ファーストビュー外の画像を遅延読み込みすることで、初期表示速度を大幅に改善できます。Claude Codeを使えば、ブラウザネイティブの方法からカスタム実装まで、最適な画像読み込み戦略を構築できます。
ネイティブLazy Loadingの活用
最もシンプルな方法はHTMLのloading属性です。
> Next.jsのImageコンポーネントのような最適化された画像コンポーネントを作って。
> lazy loading、プレースホルダー、レスポンシブ対応を含めて。
import { useState, useRef, useEffect } from 'react';
interface OptimizedImageProps {
src: string;
alt: string;
width: number;
height: number;
placeholder?: 'blur' | 'skeleton' | 'none';
blurDataURL?: string;
sizes?: string;
priority?: boolean;
className?: string;
}
function OptimizedImage({
src, alt, width, height, placeholder = 'skeleton',
blurDataURL, sizes, priority = false, className = '',
}: OptimizedImageProps) {
const [loaded, setLoaded] = useState(false);
const [error, setError] = useState(false);
const imgRef = useRef<HTMLImageElement>(null);
// 高優先度画像はプリロード
useEffect(() => {
if (priority) {
const link = document.createElement('link');
link.rel = 'preload';
link.as = 'image';
link.href = src;
document.head.appendChild(link);
return () => { document.head.removeChild(link); };
}
}, [src, priority]);
const aspectRatio = `${width} / ${height}`;
return (
<div
className={`relative overflow-hidden ${className}`}
style={{ aspectRatio }}
>
{/* プレースホルダー */}
{!loaded && placeholder === 'blur' && blurDataURL && (
<img
src={blurDataURL}
alt=""
aria-hidden="true"
className="absolute inset-0 w-full h-full object-cover blur-lg scale-110"
/>
)}
{!loaded && placeholder === 'skeleton' && (
<div className="absolute inset-0 animate-pulse bg-gray-200 dark:bg-gray-700" />
)}
{/* メイン画像 */}
<img
ref={imgRef}
src={src}
alt={alt}
width={width}
height={height}
sizes={sizes}
loading={priority ? 'eager' : 'lazy'}
decoding="async"
onLoad={() => setLoaded(true)}
onError={() => setError(true)}
className={`w-full h-full object-cover transition-opacity duration-300 ${
loaded ? 'opacity-100' : 'opacity-0'
}`}
/>
{error && (
<div className="absolute inset-0 flex items-center justify-center bg-gray-100 text-gray-400">
画像を読み込めません
</div>
)}
</div>
);
}
Intersection Observerによるカスタム遅延読み込み
function useLazyImage(threshold = 0.1) {
const [isVisible, setIsVisible] = useState(false);
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
const element = ref.current;
if (!element) return;
const observer = new IntersectionObserver(
([entry]) => {
if (entry.isIntersecting) {
setIsVisible(true);
observer.unobserve(element);
}
},
{ threshold, rootMargin: '200px 0px' } // 200px手前から読み込み開始
);
observer.observe(element);
return () => observer.disconnect();
}, [threshold]);
return { ref, isVisible };
}
// Usage example
function LazyImage({ src, alt, ...props }: ImgHTMLAttributes<HTMLImageElement>) {
const { ref, isVisible } = useLazyImage();
return (
<div ref={ref}>
{isVisible ? (
<img src={src} alt={alt} {...props} />
) : (
<div className="animate-pulse bg-gray-200" style={{ aspectRatio: '16/9' }} />
)}
</div>
);
}
画像フォーマットの最適化
function ResponsiveImage({ src, alt, width, height }: ImageProps) {
const baseName = src.replace(/\.[^.]+$/, '');
return (
<picture>
<source srcSet={`${baseName}.avif`} type="image/avif" />
<source srcSet={`${baseName}.webp`} type="image/webp" />
<img
src={src}
alt={alt}
width={width}
height={height}
loading="lazy"
decoding="async"
className="w-full h-auto"
/>
</picture>
);
}
ぼかしプレースホルダーの生成
// ビルド時にぼかしプレースホルダーを生成
import sharp from 'sharp';
async function generateBlurDataURL(imagePath: string): Promise<string> {
const buffer = await sharp(imagePath)
.resize(10, 10, { fit: 'inside' })
.blur()
.toBuffer();
return `data:image/png;base64,${buffer.toString('base64')}`;
}
Summary
Claude Codeを使えば、ネイティブLazy LoadingからIntersection Observer、画像フォーマット最適化まで包括的な画像読み込み戦略を構築できます。スケルトン表示との連携はスケルトンローディングを、画像処理全般は画像処理の記事を参照してください。
画像の最適化手法についてはweb.dev - Optimize imagesが参考になります。
Free PDF: Claude Code Cheatsheet in 5 Minutes
Just enter your email and we'll send you the single-page A4 cheatsheet right away.
We handle your data with care and never send spam.
Level up your Claude Code workflow
50 battle-tested prompt templates you can copy-paste into Claude Code right now.
About the Author
Masa
Engineer obsessed with Claude Code. Runs claudecode-lab.com, a 10-language tech media with 2,000+ pages.
Related Posts
7 CLAUDE.md Templates for Claude Code You Can Copy Into Real Projects
Copy-paste 7 practical CLAUDE.md templates for solo apps, content sites, APIs, teams, and legacy codebases, plus the failure cases to avoid.
Claude Code Approval and Sandbox Guide | Safe Daily Settings for Real Work
Learn how to split Claude Code actions into allow, ask, deny, and sandboxed workflows with working settings, hooks, and rollout examples.
Complete Beginner's Guide to Claude Code 2026 | 7 Steps from Zero to Production-Ready
A complete beginner's guide for first-time Claude Code users. From installation to integrating it into your real development workflow — covering every pitfall Masa ran into when starting out.
Related Products
50 Battle-Tested Claude Code Prompt Templates
Copy, paste, ship. 50 production-ready prompts.
Use proven prompts for code review, refactoring, testing, documentation, debugging, architecture, and incident response.
The Complete Claude Code Setup & Configuration Guide
From install to team-ready workflow.
A practical guide to installation, CLAUDE.md, hooks, MCP servers, permissions, IDE setup, and CI/CD workflows.