如何Implement Lazy Loading Images:Claude Code 实战指南
学习如何implement lazy loading images:Claude Code 实战. 包含实用代码示例和分步指导。
图片懒加载の重要性
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')}`;
}
总结
借助 Claude Code,ネイティブLazy LoadingからIntersection Observer、图片フォーマット优化まで包括的な图片加载戦略を构建可以。スケルトン显示との联动はスケルトンローディングを、图片処理全般は图片処理の文章。
图片の优化手法相关内容请参阅web.dev - Optimize imagesが参考になります。
#Claude Code
#遅延読み込み
#image optimization
#performance
#React
Related Posts
Tips & Tricks
Tips & Tricks
10 个技巧让你的 Claude Code 生产力翻三倍
分享 10 个实用的 Claude Code 使用技巧。从提示词策略到工作流优化,这些方法让你今天就能提升效率。
Tips & Tricks
Tips & Tricks
Canvas/WebGL Optimization:Claude Code 实战指南
了解canvas/webgl optimization:Claude Code 实战. 包含实用技巧和代码示例。
Tips & Tricks
Tips & Tricks
Markdown Implementation:Claude Code 实战指南
了解markdown implementation:Claude Code 实战. 包含实用技巧和代码示例。