Chargement paresseux des images avec Claude Code
Découvrez chargement paresseux des images avec Claude Code. Conseils pratiques et exemples de code inclus.
画像遅延読み込みの重要性
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が参考になります。
Related Posts
10 astuces pour tripler votre productivité avec Claude Code
Découvrez 10 astuces pratiques pour tirer le meilleur parti de Claude Code. Des stratégies de prompts aux raccourcis de workflow, ces techniques amélioreront votre efficacité dès aujourd'hui.
Optimisation Canvas/WebGL avec Claude Code
Découvrez l'optimisation Canvas/WebGL avec Claude Code. Conseils pratiques et exemples de code inclus.
Traitement Markdown avec Claude Code
Découvrez traitement Markdown avec Claude Code. Conseils pratiques et exemples de code inclus.