Lazy Load Images WordPress

User
Lazy load archive page img wordpress js custom
Assistant
To implement lazy loading for images on an archive page in WordPress using custom JavaScript, follow these steps:

### Steps to Implement Lazy Loading:

#### 1. **Prepare Your HTML**
Update your image elements in the WordPress archive template to include a `data-src` attribute for the actual image URL and a placeholder image for immediate rendering. Example:

<img class="lazy" data-src="<?php echo esc_url( $image_url ); ?>" src="placeholder.jpg" alt="<?php the_title(); ?>">

#### 2. **Enqueue Custom JavaScript**
Add custom JavaScript for lazy loading in your theme or plugin.

– Add the script in `functions.php`:

function enqueue_lazy_load_script() {
    wp_enqueue_script(
        'lazy-load-script',
        get_template_directory_uri() . '/js/lazy-load.js',
        array('jquery'),
        null,
        true
    );
}
add_action('wp_enqueue_scripts', 'enqueue_lazy_load_script');

#### 3. **Write the JavaScript**
Create a `lazy-load.js` file in your theme's `js` folder. Here's an example of a custom lazy load script:

document.addEventListener("DOMContentLoaded", function () {
    const lazyImages = document.querySelectorAll("img.lazy");

    const imageObserver = new IntersectionObserver((entries, observer) => {
        entries.forEach((entry) => {
            if (entry.isIntersecting) {
                const img = entry.target;
                img.src = img.getAttribute("data-src");
                img.classList.remove("lazy");
                observer.unobserve(img);
            }
        });
    });

    lazyImages.forEach((image) => {
        imageObserver.observe(image);
    });
});

#### 4. **Add a Placeholder Image**
Use a lightweight placeholder image (e.g., 1×1 transparent pixel or low-resolution image) for `src` in the initial HTML:

<img class="lazy" data-src="<?php echo esc_url( $image_url ); ?>" src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==" alt="<?php the_title(); ?>">

#### 5. **Optional: Add Styles**
Add some CSS to prevent layout shifts during image loading:

img.lazy {
    opacity: 0;
    transition: opacity 0.3s ease-in-out;
}

img.lazy-loaded {
    opacity: 1;
}

Modify your JavaScript to add a `lazy-loaded` class once the image is loaded:

img.onload = () => img.classList.add("lazy-loaded");

### Testing the Implementation
1. Navigate to your archive page.
2. Open the browser's Developer Tools and check the `Network` tab.
3. Scroll through the page, and observe that images are loaded only when they enter the viewport.

This approach ensures that only visible images are loaded, optimizing page speed and improving performance.

Leave a Comment

Your email address will not be published. Required fields are marked *