js

Thursday, December 7, 2023

Develop a PHP script that implements lazy loading for images. Additionally, incorporate JavaScript where necessary to enhance the lazy loading functionality.

 Q. Develop a PHP script that implements lazy loading for images. Additionally, incorporate JavaScript where necessary to enhance the lazy loading functionality.

Hint: Consider creating a PHP file, such as lazy_loading.php, that generates HTML markup for images. Implement lazy loading by utilizing HTML attributes and incorporate JavaScript to manage the loading of images on the client side.

Solution:
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Lazy Loading Images</title>
</head>

<body>

    <?php
    // Array of image filenames
    $str = "image2.jpg,image3.jpg,image1.jpg,image4.jpg";
    $imageFilenames = explode(",", $str);

    foreach ($imageFilenames as $filename) {
        // Generate data-src attribute with the actual image source
        $dataSrc = "images/$filename";

        // Output the image element with the data-src attribute
        echo "<img loading='lazy' data-src='$dataSrc' alt='Lazy Loaded Image'>\n";
    }
    ?>

    <script>
        // JavaScript code to handle lazy loading
        document.addEventListener("DOMContentLoaded", function() {
            var lazyImages = document.querySelectorAll("img[data-src]");

            lazyImages.forEach(function(img) {
                img.src = img.dataset.src;
                img.removeAttribute("data-src");
            });
        });
    </script>

</body>

</html>

No comments:

Post a Comment

SEBA HSLC Question Paper Science 2023