Manuals

Script for lazy loading images

Here’s a simple script for lazy loading images on a website using JavaScript. This approach will improve page load performance by only loading images when they are in the viewport.

HTML Example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Lazy Load Images</title>
    <style>
        .lazy {
            display: block;
            width: 100%; /* Adjust as necessary */            height: auto; /* Maintain aspect ratio */            background: #f0f0f0; /* Placeholder color */        }
    </style>
</head>
<body>

    <h1>Lazy Loading Images Example</h1>
    <img class="lazy" data-src="image1.jpg" alt="Image 1" />
    <img class="lazy" data-src="image2.jpg" alt="Image 2" />
    <img class="lazy" data-src="image3.jpg" alt="Image 3" />
    <img class="lazy" data-src="image4.jpg" alt="Image 4" />
    <img class="lazy" data-src="image5.jpg" alt="Image 5" />

    <script src="lazyload.js"></script>
</body>
</html>

JavaScript (lazyload.js)

document.addEventListener("DOMContentLoaded", function() {
    const lazyImages = document.querySelectorAll('img.lazy');
    
    const observerOptions = {
        root: null, // Use the viewport as the root
        rootMargin: '0px',
        threshold: 0.1 // Trigger when 10% of the image is in view
    };

    const imageObserver = new IntersectionObserver((entries, observer) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                const img = entry.target;
                // Replace the placeholder with the actual image
                img.src = img.dataset.src;
                img.classList.remove('lazy');
                // Stop observing the image after it's loaded
                observer.unobserve(img);
            }
        });
    }, observerOptions);

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

Explanation

  1. HTML Structure: Each image uses the class lazy and a data-src attribute to hold the actual image URL. This tells the script not to load the image until it is visible.
  2. CSS Styles: Use basic styles to give a placeholder appearance for images that are being lazy-loaded.
  3. JavaScript Logic:
    • The script waits for the DOM to load before executing.
    • It selects all images with the class lazy.
    • An IntersectionObserver is created to watch when the images enter the viewport.
    • When an image is intersected, the script sets its src attribute to the value in data-src, causing the image to load.
    • After loading, the script removes the lazy class and stops observing that image.

Usage

Make sure to link the lazyload.js script in your HTML document. You can adjust the threshold and rootMargin based on your needs to control when the images start loading as they come into view.

This setup ensures a more efficient loading process, especially for pages with many images.

Victoria

Im just a girl who hanging around with her friends ;)

Recent Posts

Building Your Next Project with wp-scripts: A Comprehensive Guide

WordPress development has evolved significantly, and modern tooling plays a crucial role in creating efficient…

1 week ago

Script for automatically informing search engines about new content on website

I. Project Overview The goal is to automate the process of notifying search engines (like…

2 weeks ago

Creating an XML sitemap script with PHP, designed for automated updates via CRON

1. Database Structure (MySQL) We'll need a database table to store information about our website's…

2 weeks ago

Comprehensive guide on building a URL shortening script

This explanation aims to provide a solid foundation for understanding the process and implementing your…

2 weeks ago

Guide on building a real-time website chat script

Okay, here's a comprehensive guide on building a real-time website chat script using PHP, HTML,…

2 weeks ago

Comprehensive guide on creating a simple website analytics system

Comprehensive guide on creating a simple website analytics system using PHP, HTML, CSS, JavaScript, and…

2 weeks ago