Lazy Load Images using PHP and JavaScript

On 1/23/2017

Hi! In today's post let's see how to lazy load images using php and javascript. Lazy loading technique has been used by several websites these days especially sites with high graphics content. It just delays the loading process of web page images until the user move on to that specific area of the page. If you have too many images on a page, it takes more time to load. Depending on the graphics size this may take from few to several seconds. Not to say site visitors don't like to be kept waiting and may exit the site without visiting.

Studies show blogs and websites with lesser loading time gets more traffic from search engines. E-commerce sites and gallery pages are the usual victims of longer page loading as they contain so many images. For them lazy loading the images will surely help.

When a visitor lands on a page, lazy loading will only load images that are present in the viewport at start. Rest of the images will start appearing when user scrolls down the page. Let's see how to implement this lazy loading image technique in php and plain JavaScript.

lazy-load-images-php-javascript

How to Lazy Load Images using PHP & JavaScript?

A while back I have shared a tutorial on KMS about creating dynamic image gallery in php. It will load gallery images dynamically from a given folder with the help of php code. I'm going use the same example here and show you how to add lazy loading technique to it.

Let's be clear about one thing. We don't need bloated jquery library here. Just good-old java script is enough. To simplify the process I'm going to use Blazy JavaScript Library which is written completely in javascript.

Blazy is light-weight and less than 1.2KB minified and gzipped. It lets you lazy load and multi-serve images without dwelling into the technical stuff. Follow the below steps to implement lazy loading using b-lazy.

Step 1: First and foremost download the latest blazy javascript library and move the minified js file to your application root.

Step 2: Then create a php file 'gallery.php' and add this basic html markup to it.

<!DOCTYPE html>
<html>
<head>
    <title>Lazy Load Images using PHP & Javascript</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
</body>
</html>

Step 3: Next load the blazy Java Script library at the end of the markup.

<script src="js/blazy.min.js" type="text/javascript"></script>

Step 4: Then you have to add a little php script to load the gallery images one by one from a folder.

<?php
$path = "images/"; // set folder path

// count no. of images in folder
$cnt = count(glob($path . "*.{jpg,jpeg}", GLOB_BRACE));

if ($cnt > 0) {
    $fp = opendir($path);
    while ($image = readdir($fp)) {
        $ext = pathinfo($image, PATHINFO_EXTENSION);
        $allowed_ext = ['jpg', 'jpeg'];
        if (in_array($ext, $allowed_ext)) {
            $image_path = $path . $image; ?>
            <img class="b-lazy" src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" data-src="<?php echo $image_path; ?>" alt="<?php echo $image; ?>" />
        <? }
    }
    closedir($fp);
} else {
    echo "Sorry! No images available in gallery!";
}
?>

Since we have to lazy load images, you should not add the real image source directly to src attribute. Instead you must add it to data-src attribute and add a place holder image to 'src'. As for the place holder image, adding base64 encoded transparent gif will reduce any additional requests to server.

Finally you have to add .b-lazy css selector to <img> tag.

Step 5: Now you have to initialize the 'blazy' library like this.

<script type="text/javascript">
    ;(function() {
        var bLazy = new Blazy();
    })();
</script>

Step 6: This is the final step but optional. Here I would like to add some nice transition effects to lazy loaded images. Blazy doesn't support animations by itself but it doesn't mean you cannot add some css styles to it.

<style type="text/css">
    .b-lazy {
       transform: scale(3);
       transition: all 500ms;
       opacity:0;
    }
    .b-loaded {
       transform: scale(1);
       opacity:1;
    }
</style>

Done! Now you have everything in place and successfully implemented lazy loading images in php & javascript.

Here's the Complete Script for Gallery.php:

<!DOCTYPE html>
<html>
<head>
    <title>Lazy Load Images using PHP & Javascript</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style type="text/css">
    .b-lazy {
       transform: scale(3);
       transition: all 500ms;
       opacity:0;
    }
    .b-loaded {
       transform: scale(1);
       opacity:1;
    }
    </style>
</head>
<body>
    <?php
    // set folder path
    $path = "images/";

    // count no. of images in dir
    $cnt = count(glob($path . "*.{jpg,jpeg}", GLOB_BRACE));

    if ($cnt > 0) {
        $fp = opendir($path);
        while ($image = readdir($fp)) {
            $ext = pathinfo($image, PATHINFO_EXTENSION);
            $allowed_ext = ['jpg', 'jpeg'];
            if (in_array($ext, $allowed_ext)) {
                $image_path = $path . $image; ?>
                <img class="b-lazy" src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" data-src="<?php echo $image_path; ?>" alt="<?php echo $image; ?>" />
            <? }
        }
        closedir($fp);
    } else {
        echo "Sorry! No images available in gallery!";
    }
    ?>

    <script src="js/blazy.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        ;(function() {
            var bLazy = new Blazy();
        })();
    </script>
</body>
</html>

Lazy loading technique is fairly popular and not limited to images but to any html entity.

What are the Pros of using Lazy Loading?

  1. It improves page loading speed since it only loads images within the user viewport.
  2. Greatly improve user experience by reducing the waiting time to finish loading the entire page content.
  3. Search engines like Google give more importance to page speed these days. So if your website or blog depends on organic traffic then lazy loading would be a boon.
  4. Finally Blazy library is written on pure java script and doesn't need jquery. So no additional baggage on server.

Even though lazy loading has several advantages, the concept is still debatable and has gotten negative press among many developers.

So should you lazy load images in websites? Definitely high graphics pages would benefit by using this technique. In my opinion it's more of a convenience than requirement.

So that's all for lazy loading images in php and javascript. The technique will be suitable for pages with numerous images like gallery or home page. I hope you like this tutorial. Please share your thoughts through comments.

No comments:

Post a Comment

Contact Form

Name

Email *

Message *