Responsive images and lazy loading implementation
Implementation Methods for Responsive Images
The core of responsive images is to provide the most suitable image resources based on different device characteristics (such as screen size and resolution). Common implementation methods include:
- HTML's
srcset
andsizes
Attributes
<img
src="small.jpg"
srcset="medium.jpg 1000w, large.jpg 2000w"
sizes="(max-width: 600px) 100vw, (max-width: 1200px) 50vw, 1000px"
alt="Responsive Image Example">
picture
Element
<picture>
<source media="(min-width: 1200px)" srcset="large.jpg">
<source media="(min-width: 768px)" srcset="medium.jpg">
<img src="small.jpg" alt="Responsive Image">
</picture>
- CSS Media Queries
.banner {
background-image: url('small-bg.jpg');
}
@media (min-width: 768px) {
.banner {
background-image: url('medium-bg.jpg');
}
}
@media (min-width: 1200px) {
.banner {
background-image: url('large-bg.jpg');
}
}
Image Format Selection and Optimization
Modern image formats can significantly improve performance:
- WebP: 25-34% smaller than JPEG, supports transparency
<picture>
<source type="image/webp" srcset="image.webp">
<img src="image.jpg" alt="WebP Fallback">
</picture>
- AVIF: More efficient compression than WebP
<picture>
<source type="image/avif" srcset="image.avif">
<source type="image/webp" srcset="image.webp">
<img src="image.jpg" alt="AVIF Fallback">
</picture>
- SVG: Suitable for icons and simple graphics
<img src="logo.svg" alt="SVG Logo" width="200" height="100">
Lazy Loading Techniques
Lazy loading improves initial page load speed by delaying non-critical resources:
- Native Lazy Loading
<img src="placeholder.jpg" data-src="actual-image.jpg" loading="lazy" alt="Lazy-loaded Image">
- Intersection Observer API
const lazyImages = document.querySelectorAll('img[data-src]');
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target;
img.src = img.dataset.src;
observer.unobserve(img);
}
});
}, {
rootMargin: '200px 0px'
});
lazyImages.forEach(img => observer.observe(img));
- React Implementation Example
import { useEffect, useRef } from 'react';
function LazyImage({ src, alt }) {
const imgRef = useRef(null);
useEffect(() => {
const observer = new IntersectionObserver(([entry]) => {
if (entry.isIntersecting) {
imgRef.current.src = src;
observer.unobserve(imgRef.current);
}
});
observer.observe(imgRef.current);
return () => observer.disconnect();
}, [src]);
return <img ref={imgRef} src="placeholder.jpg" alt={alt} />;
}
Advanced Optimization Techniques
- Low-Quality Image Placeholder (LQIP)
<img
src="tiny-blurred-image.jpg"
data-src="large-image.jpg"
class="lazyload blur"
alt="LQIP Example">
<style>
.blur {
filter: blur(5px);
transition: filter 0.3s;
}
.blur.lazyloaded {
filter: blur(0);
}
</style>
- Adaptive Pixel Ratio
<img
src="image-1x.jpg"
srcset="image-2x.jpg 2x, image-3x.jpg 3x"
alt="High DPI Adaptation">
- CDN Image Processing
<img
src="https://cdn.example.com/image.jpg?width=400&quality=80"
srcset="
https://cdn.example.com/image.jpg?width=400&quality=80 400w,
https://cdn.example.com/image.jpg?width=800&quality=80 800w
"
sizes="(max-width: 600px) 100vw, 50vw"
alt="CDN Image Processing">
Performance Monitoring and Testing
- Lighthouse Audit
// Run Lighthouse tests in Chrome DevTools
// Focus on the following metrics:
// - Whether image elements have explicit width and height
// - Whether next-gen image formats are used
// - Whether offscreen images are lazy-loaded
- Chrome Performance Panel
// Use the Performance panel to record page loading
// Check image loading timing in the Network tab
// Identify render-blocking image resources
- Custom Performance Metrics
// Track image loading time
const images = document.querySelectorAll('img');
images.forEach(img => {
const start = performance.now();
img.onload = () => {
const loadTime = performance.now() - start;
console.log(`${img.src} loading time: ${loadTime}ms`);
};
});
Common Issue Solutions
- Layout Shift Issues
<!-- Use aspect ratio placeholders -->
<div style="position: relative; padding-bottom: 56.25%;">
<img
src="placeholder.jpg"
data-src="actual-image.jpg"
loading="lazy"
style="position: absolute; width: 100%; height: 100%;"
alt="Avoiding Layout Shift">
</div>
- Low-Speed Network Handling
// Adjust image quality based on network conditions
if (navigator.connection && navigator.connection.effectiveType === '2g') {
document.querySelectorAll('img[data-src-low]').forEach(img => {
img.src = img.dataset.srcLow;
});
}
- SEO Optimization
<!-- Ensure lazy-loaded images can be crawled -->
<noscript>
<img src="important-image.jpg" alt="Fallback when JS is disabled">
</noscript>
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn
上一篇:图片优化格式选择与压缩
下一篇:字体文件优化与子集化