Immerse

Immerse

github
email
twitter
youtube
zhihu

Image Progressive Loading Optimization Practice Guide

Introduction#

  • Hey, I am Immerse
  • The article was first published on my personal blog https://yaolifeng.com, for more content please follow my personal blog
  • Reprint instructions: Please indicate the original source and copyright statement at the beginning of the article!

Cause#

  • Recently launched personal blog, the fragment page has a lot of images, and the experience in image loading is very poor, it can be said to be a cliff-like drop, with no transition from 0 to 1 (this greatly affects the page layout and user experience, for images with set width and height it’s fine, but if not set, there will be a process of an image stretching high)

Coincidence#

  • On the day I was preparing to write this article, the front-end master Nan Jiu published an article, I exclaimed that big data is amazing 👍🏻 Article: Click to view
  • In this article, we will discuss several other solutions, without further ado, let's get to the point.
    • For conventional image optimization, I will not elaborate here, roughly as follows:
      • Compress images, use CSS sprites, lazy loading, preloading, CDN caching, appropriate image formats, Qiniu CDN image parameters, etc.

Exploration#

  • Below are several solutions mentioned in this article (since the personal project is based on Next, some example codes are in React)
    • (1) Use the main color of the image
    • (2) Use a specific color
    • (3) Use a thumbnail of the image
    • (4) Use blurred + compressed images
    • (5) Image placeholders

Solution 1: Use the main color of the image#

  • In daily development, our image src may be dynamic, which is a string string url, when we specify placeholder="blur", we must also add blurDataURL attribute,
import Image from 'next/image';

// Pixel GIF code adapted from https://stackoverflow.com/a/33919020/266535
const keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';

const triplet = (e1: number, e2: number, e3: number) =>
    keyStr.charAt(e1 >> 2) +
    keyStr.charAt(((e1 & 3) << 4) | (e2 >> 4)) +
    keyStr.charAt(((e2 & 15) << 2) | (e3 >> 6)) +
    keyStr.charAt(e3 & 63);

const rgbDataURL = (r: number, g: number, b: number) =>
    `data:image/gif;base64,R0lGODlhAQABAPAA${
        triplet(0, r, g) + triplet(b, 255, 255)
    }/yH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==`;

const Color = () => (
    <div>
        <h1>Image Component With Color Data URL</h1>
        <Image
            alt="Dog"
            src="/dog.jpg"
            placeholder="blur"
            blurDataURL={rgbDataURL(237, 181, 6)}
            width={750}
            height={1000}
            style={{
                maxWidth: '100%',
                height: 'auto'
            }}
        />
        <Image
            alt="Cat"
            src="/cat.jpg"
            placeholder="blur"
            blurDataURL={rgbDataURL(2, 129, 210)}
            width={750}
            height={1000}
            style={{
                maxWidth: '100%',
                height: 'auto'
            }}
        />
    </div>
);

export default Color;

Solution 2: Use a specific color#

  • In next.config.js, configure placeholder to color, and then use the backgroundColor attribute
// next.config.js
module.exports = {
    images: {
        placeholder: 'color',
        backgroundColor: '#121212'
    }
};
// Usage
<Image src="/path/to/image.jpg" alt="image title" width={500} height={500} placeholder="color" />

Solution 3: Use a thumbnail of the image#

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Progressive Image Loading</title>
        <style>
            .placeholder {
                background-color: #f6f6f6;
                background-size: cover;
                background-repeat: no-repeat;
                position: relative;
                overflow: hidden;
            }

            .placeholder img {
                position: absolute;
                opacity: 0;
                top: 0;
                left: 0;
                width: 100%;
                transition: opacity 1s linear;
            }

            .placeholder img.loaded {
                opacity: 1;
            }

            .img-small {
                filter: blur(50px);
                transform: scale(1);
            }
        </style>
    </head>
    <body>
        <div
            class="placeholder"
            data-large="https://qncdn.mopic.mozigu.net/work/143/24/42b204ae3ade4f38/1_sg-uLNm73whmdOgKlrQdZA.jpg"
        >
            <img
                src="https://qncdn.mopic.mozigu.net/work/143/24/5307e9778a944f93/1_sg-uLNm73whmdOgKlrQdZA.jpg"
                class="img-small"
            />
            <div style="padding-bottom: 66.6%"></div>
        </div>
    </body>
</html>
<script>
    window.onload = function () {
        var placeholder = document.querySelector('.placeholder'),
            small = placeholder.querySelector('.img-small');

        // 1. Show small image and load
        var img = new Image();
        img.src = small.src;
        img.onload = function () {
            small.classList.add('loaded');
        };

        // 2. Load large image
        var imgLarge = new Image();
        imgLarge.src = placeholder.dataset.large;
        imgLarge.onload = function () {
            imgLarge.classList.add('loaded');
        };
        placeholder.appendChild(imgLarge);
    };
</script>

Solution 4: Use blurred + compressed images#

// progressive-image.tsx
'use client';

import React, { useState, useEffect } from 'react';
import imageCompression from 'browser-image-compression';

interface ProgressiveImageProps {
    src: string;
    alt?: string;
    width?: number;
    height?: number;
    layout?: 'fixed' | 'responsive' | 'fill' | 'intrinsic';
    className?: string;
    style?: React.CSSProperties;
}

export const ProgressiveImage: React.FC<ProgressiveImageProps> = ({
    src,
    alt = '',
    width,
    height,
    layout = 'responsive',
    className = '',
    style = {}
}) => {
    const [currentSrc, setCurrentSrc] = useState<string>(src);
    const [isLoading, setIsLoading] = useState<boolean>(true);
    const [blurLevel, setBlurLevel] = useState<number>(20);

    useEffect(() => {
        let isMounted = true;

        const loadImage = async () => {
            try {
                // Load and compress the original image
                const response = await fetch(src);
                const blob = await response.blob();

                // Generate low-quality preview image
                const tinyOptions = {
                    maxSizeMB: 0.0002,
                    maxWidthOrHeight: 16,
                    useWebWorker: true,
                    initialQuality: 0.1
                };

                const tinyBlob = await imageCompression(blob, tinyOptions);
                if (isMounted) {
                    const tinyUrl = URL.createObjectURL(tinyBlob);
                    setCurrentSrc(tinyUrl);
                    // Start gradually reducing blur
                    startSmoothTransition();
                }

                // Load the original image
                const highQualityImage = new Image();
                highQualityImage.src = src;
                highQualityImage.onload = () => {
                    if (isMounted) {
                        setCurrentSrc(src);
                        // Continue smooth transition when high-quality image is loaded
                        setTimeout(() => {
                            setIsLoading(false);
                        }, 100);
                    }
                };
            } catch (error) {
                console.error('Error loading image:', error);
                if (isMounted) {
                    setCurrentSrc(src);
                    setIsLoading(false);
                }
            }
        };

        const startSmoothTransition = () => {
            // Transition from 20px blur to 10px
            const startBlur = 20;
            const endBlur = 10;
            const duration = 1000; // 1 second
            const steps = 20;
            const stepDuration = duration / steps;
            const blurStep = (startBlur - endBlur) / steps;

            let currentStep = 0;

            const interval = setInterval(() => {
                if (currentStep < steps && isMounted) {
                    setBlurLevel(startBlur - blurStep * currentStep);
                    currentStep++;
                } else {
                    clearInterval(interval);
                }
            }, stepDuration);
        };

        setIsLoading(true);
        setBlurLevel(20);
        loadImage();

        return () => {
            isMounted = false;
            if (currentSrc && currentSrc.startsWith('blob:')) {
                URL.revokeObjectURL(currentSrc);
            }
        };
    }, [src]);

    const getContainerStyle = (): React.CSSProperties => {
        const baseStyle: React.CSSProperties = {
            position: 'relative',
            overflow: 'hidden'
        };

        switch (layout) {
            case 'responsive':
                return {
                    ...baseStyle,
                    maxWidth: width || '100%',
                    width: '100%'
                };
            case 'fixed':
                return {
                    ...baseStyle,
                    width: width,
                    height: height
                };
            case 'fill':
                return {
                    ...baseStyle,
                    width: '100%',
                    height: '100%',
                    position: 'absolute',
                    top: 0,
                    left: 0
                };
            case 'intrinsic':
                return {
                    ...baseStyle,
                    maxWidth: width,
                    width: '100%'
                };
            default:
                return baseStyle;
        }
    };

    const getImageStyle = (): React.CSSProperties => {
        const baseStyle: React.CSSProperties = {
            filter: isLoading ? `blur(${blurLevel}px)` : 'none',
            transition: 'filter 0.8s ease-in-out', // Increase transition time
            transform: 'scale(1.1)', // Slightly enlarge to prevent edges during blur
            ...style
        };

        switch (layout) {
            case 'responsive':
                return {
                    ...baseStyle,
                    width: '100%',
                    height: 'auto',
                    display: 'block'
                };
            case 'fixed':
                return {
                    ...baseStyle,
                    width: width,
                    height: height
                };
            case 'fill':
                return {
                    ...baseStyle,
                    width: '100%',
                    height: '100%',
                    objectFit: 'cover'
                };
            case 'intrinsic':
                return {
                    ...baseStyle,
                    width: '100%',
                    height: 'auto'
                };
            default:
                return baseStyle;
        }
    };

    return (
        <div className={`${className}`} style={getContainerStyle()}>
            {currentSrc && <img src={currentSrc} alt={alt} style={getImageStyle()} />}
        </div>
    );
};
// Usage
<ProgressiveImage
    src={photo}
    alt={short.title}
    width={300}
    height={250}
    layout="responsive"
    className="h-full min-h-[150px]"
/>

Solution 5: Image placeholders#

  • Next.js's next/image component placeholder attribute provides an option blur, which defaults to empty
    • blur will generate a blurred preview image (but this option will increase the initial loading time because it takes time to generate the blurred image)
    • Note: If placeholder="blur", you must use the import static import method for images, so that Next.js will preprocess the images for progressive loading
import Image from 'next/image';
import mountains from '/public/mountains.jpg';

const PlaceholderBlur = () => (
    <div>
        <h1>Image Component With Placeholder Blur</h1>
        <Image
            alt="Mountains"
            src={mountains}
            placeholder="blur"
            width={700}
            height={475}
            style={{
                maxWidth: '100%',
                height: 'auto'
            }}
        />
    </div>
);

export default PlaceholderBlur;

Conclusion#

  • The first impression of a product is very important, and a good user experience is essential for a product.
  • Thank you for reading, see you next time!
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.