Frontend Development 5 min read

Implementing Image Lazy Loading in PHP: A Step‑by‑Step Guide

This article explains how to implement image lazy loading in PHP by extracting image URLs, generating placeholder tags with data-src attributes, monitoring scroll events via JavaScript, and applying CSS transitions, providing a step‑by‑step guide with complete code examples to improve page load performance.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Implementing Image Lazy Loading in PHP: A Step‑by‑Step Guide

With the development of the Internet, the number of images on web pages has increased, putting pressure on page load speed. To improve user experience and reduce load time, we can use image lazy loading. Lazy loading delays image loading until the user scrolls to the visible area, reducing load time and enhancing experience.

When writing PHP web pages, we can write functions to optimize lazy loading. Below we detail how to achieve image lazy loading with PHP functions.

Step 1: Get all image URLs

First, we need to obtain all image links on the current page. This can be done using preg_match_all and a regular expression, as shown:

<code>function get_image_urls($html) {
    $pattern = '/<img[^>]+src=["\']([^"\']+)["\'][^>]*>/i';
    preg_match_all($pattern, $html, $matches);
    return $matches[1];
}

$html = file_get_contents('http://example.com');
$image_urls = get_image_urls($html);
</code>

Step 2: Generate image placeholders

Before the page finishes loading, we need to generate a placeholder for each image to be lazy loaded, avoiding layout reflow. We can use the &lt;img&gt; tag's data-src attribute to store the real image URL and display a placeholder.

<code>function generate_placeholder($image_url) {
    return '<img src="placeholder.jpg" class="lazy" data-src="' . $image_url . '">';
}

$placeholders = array_map('generate_placeholder', $image_urls);
</code>

In the above code, placeholder.jpg is a placeholder image that can be replaced as needed, and the lazy class identifies images to be loaded later.

Step 3: Listen to scroll events

We need to monitor user scroll behavior; when the user scrolls to an image's visible area, we assign the real link to the src attribute to load the image.

<code>function load_image($image_url) {
    echo "<script>
        window.addEventListener('scroll', function() {
            var images = document.querySelectorAll('.lazy');
            Array.prototype.forEach.call(images, function(image) {
                var rect = image.getBoundingClientRect();
                if (rect.top >= 0 && rect.bottom <= (window.innerHeight || document.documentElement.clientHeight)) {
                    image.src = image.dataset.src;
                    image.classList.remove('lazy');
                }
            });
        });
    </script>";
}

array_map('load_image', $image_urls);
</code>

In the above code, JavaScript listens for scroll events and determines whether each image is within the viewport before loading it.

Step 4: Style optimization

To improve user experience, we can add a progressive loading effect such as a fade‑in/out using CSS.

<code>.lazy {
    opacity: 0;
    transition: opacity 0.3s;
}

.lazy.show {
    opacity: 1;
}
</code>

In CSS, we set a transition for the .lazy class. When the image finishes loading, we add the .show class to make it visible.

By using the PHP functions above, we can implement image lazy loading: first retrieve all image URLs, then generate placeholders, monitor scroll events to load images, and apply style optimizations. This effectively reduces page load time and enhances user experience.

frontendImage OptimizationJavaScriptlazy-loading
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.