Image Performance Optimization: Responsive Delivery, Modern Formats, and the DPR Sweet Spot
This article covers another major area of performance optimization — “Image Performance Optimization.”
Images are usually the largest and most bandwidth-hungry resources on a webpage. The core idea is: “Use various techniques to make the browser download the fewest image bytes possible without sacrificing visible image quality.”
The main content can be summarized into the following four core technical dimensions:
1. Responsive Images and Size Optimization (Dimensions & Density)
Core Pain Point: Because phones and computers have different Device Pixel Ratios (DPR, e.g., Retina screens have DPR=2 or 3) and different screen widths, you cannot send the same high-resolution large image to all devices (too wasteful of data) or a small image (it will look blurry on high-DPR screens).
Solutions:
srcsetandsizesattributes: Usesrcsetto provide image candidates with different resolutions/widths (e.g.,1000windicates an intrinsic width of 1000 pixels), and usesizesto tell the browser the image's layout width under different viewports. Let the browser calculate and download the most suitable one.<picture>element: More advanced than<img>. You can use<source media="...">to force the browser to switch to images of different sizes or even different crop orientations at specific screen sizes (or high DPR).
2. Modern File Formats and Compression (Formats & Compression)
Next-Gen Formats: Strongly recommends WebP and AVIF. They have higher compression rates than traditional JPEG and PNG (AVIF can save over 50% in file size compared to JPEG at the same quality).
Format Fallback Strategy: Use the nested tag feature of
<picture>to prioritize letting the browser read AVIF, then WebP if not recognized, and finally fall back to traditional JPEG.Lossy vs Lossless:
- Lossy Compression (JPEG, WebP, AVIF): Suitable for colorful photos, achieving huge file size reductions by discarding color details that are barely noticeable to the human eye.
- Lossless Compression (PNG, GIF, WebP, AVIF): Suitable for line art and images with text, compressing without losing any pixel data.
3. Server-Side Dynamic Delivery (Content Negotiation)
- Accept Request Header: When a browser requests an image, it includes an HTTP request header like
Accept: image/avif,image/webp,.... - Automatic Optimization: An advanced technique used by large companies is to intercept requests on the backend server or image CDN. If the user's browser is found to support AVIF, even if the HTML contains
src="pic.jpg", the backend will automatically return thepic.avifformat. This keeps the frontend HTML code clean.
4. Browser Rendering and Loading Control (Loading & Decoding)
loading="lazy"(Lazy Loading): Extremely important. Adding this attribute prevents images not in the initial viewport (off-screen) from downloading immediately; they load only when the user scrolls near them. This instantly saves a lot of initial bandwidth.decoding="async"(Async Decoding): Tells the browser to decode the image's data stream into pixels in the background, without blocking the main thread from rendering other text or layout. Very useful for high-resolution large images.
Summary: The previous chapter discussed using "resource hints" to control download timing, while this chapter discusses using "adaptive techniques" to control the size of the resource itself. Large companies typically combine loading="lazy" (for off-screen delay) + modern formats (AVIF/WebP) + responsive dimensions (srcset) for image optimization.
Questions
What is DPR? Why do different screens require different versions of the same image, and how do you calculate the right one?
This is another extremely core topic in frontend performance optimization and mobile adaptation. Senior interviewers at large companies love using it to test your low-level understanding of "mobile physical pixels and logical pixels."
Let's break down DPR to see how it troubles frontend developers and how to calculate and optimize for it.
1. What exactly is DPR (Device Pixel Ratio)?
DPR stands for Device Pixel Ratio. Its formula is very simple:
DPR = Physical Pixels (Device Pixels) / Logical Pixels (CSS Pixels)
- Logical Pixels (CSS Pixels): The
width: 300pxwe write in code. It is a "virtual unit" in the browser. - Physical Pixels: The actual number of "light-emitting particles (LED dots)" that make up a phone screen.
💡 Why does this exist?
Before 2010 (the iPhone 3 era), 1px of CSS logical pixel = 1 physical light-emitting dot, meaning DPR=1. But in 2010, the iPhone 4 introduced the Retina screen. Its physical size was the same as the iPhone 3, but Apple crammed in twice the number of physical light-emitting dots.
If 1px CSS pixel still corresponded to 1 physical light-emitting dot, the entire webpage would appear shrunk to half its size on the iPhone 4.
So Apple invented a grid mapping: on the iPhone 4, 1px of CSS logical pixel corresponds to 2 physical pixels horizontally and 2 physical pixels vertically. In other words, 2×2=4 physical pixels are used to render 1 CSS pixel. This way, the webpage size remains the same, but text and lines become extremely sharp and free of jagged edges. This is called DPR=2.
2. Why do different screens require different versions of the same image?
This is the root cause of "why images look blurry" or "why data is wasted."
An image is composed of a grid of "pixels (intrinsic dimensions)." Suppose you write a container in your page with width: 500px; height: 500px;.
On a standard computer screen with DPR = 1: The container actually needs 500x500 physical pixels. You give it a 500x500 pixel image, and it's a perfect one-to-one match, so the picture is very clear.
On a high-end phone screen with DPR = 2: Because DPR=2, this 500x500 CSS container actually occupies 1000x1000 physical light-emitting dots on the phone screen.
- If you still give it a 500x500 image: The image has only 250,000 pixels of information but needs to fill 1,000,000 light-emitting dots. The browser has to stretch and enlarge the image, making it immediately blurry.
- If you give it a 1000x1000 image: The image pixels and physical light-emitting dots match one-to-one, making the image very sharp and clear on the phone.
On a super flagship phone with DPR = 3: This container actually needs 1500x1500 physical light-emitting dots. You would need to give it a 1500x1500px image for the best result.
⚠️ The contradiction arises:
Can't we just send everyone the 1500x1500px ultra-HD image? No! If a user with an old DPR = 1 computer downloads a 1500x1500px image, their screen can only display 500x500. The browser will downsample (compress) it, and the user won't see any visible difference, but they will have wasted 9 times the file size in downloads (the area ratio is 3×3=9), wasting the large company's expensive CDN bandwidth and the user's mobile data.
3. How to calculate and find this "sweet spot"?
The core optimization strategy of large companies is: Adaptive delivery — calculate the device's DPR and container width, and give it exactly what it needs.
There are two mainstream calculation and implementation approaches in the industry:
Approach 1: Modern HTML5 Tag Auto-Calculation (Srcset + Sizes)
Let the browser do the calculation. You just prepare images of various sizes and provide hints in the code:
HTML
<img
src="img-500.jpg"
sizes="(min-width: 768px) 500px, 100vw"
srcset="img-500.jpg 500w, img-1000.jpg 1000w, img-1500.jpg 1500w"
alt="example"
>
The browser's calculation logic:
- A user is using an iPhone 13, screen width 390px, DPR=3.
- The browser reads
sizes: the viewport is currently less than 768px, so the image width is100vw(i.e., full screen width of 390px). - The browser starts calculating the physical pixel requirement: 390px × 3 (DPR) = 1170 physical pixels.
- The browser looks at the
srcsetcandidates: there are 500w, 1000w, 1500w.1000wis slightly insufficient (would be blurry), and the closest one that meets the requirement is1500w. - Result: The browser automatically decides to download
img-1500.jpg.
Approach 2: Image CDN Dynamic Cropping (Most Common in Large Companies)
Large companies (like Alibaba, Tencent, ByteDance) all have dedicated image CDN services. The frontend can calculate the current device's DPR via JS, then concatenate URL parameters to request the image from the backend.
JavaScript
// 1. Get the current device's DPR
const dpr = window.devicePixelRatio || 1;
// 2. Assume the image container's CSS width is 300px in the current layout
const containerWidth = 300;
// 3. Calculate the perfect physical image width
const targetWidth = containerWidth * dpr; // If dpr is 2, this is 600
// 4. Dynamically concatenate Alibaba Cloud/Tencent Cloud CDN cropping parameters
const imageUrl = `https://cdn.example.com/product.jpg?x-oss-process=image/resize,w_${targetWidth}`;
// 5. Assign this URL to the img tag
myImage.src = imageUrl;
💡 Follow-up: The human eye has limits (a money-saving trick for large companies)
The interviewer might dig deeper: "Since DPR = 3 requires a 3x image, do we need to pursue infinite sharpness?"
- The standard answer from large companies: No, DPR = 2 is the most cost-effective sweet spot.
- Scientific research shows that at a normal phone viewing distance, the human eye can barely distinguish the quality difference between DPR = 2 and DPR = 3.
- Therefore, to save expensive bandwidth costs, large companies usually implement a truncation optimization during calculation: for devices with DPR >= 2, they uniformly return only a 2x size image (capping the target limit at DPR=2). This ensures the image is never blurry while cutting the massive bandwidth overhead brought by 3x large images.