Lazy loading images with CDN recipes


  • DADI

    Images are amongst the most common culprits of poor performance in websites, as they often require sending several megabytes of data across the wire for a single asset. When the network conditions are less than ideal, this can have a huge impact on load times and potentially make the website unusable.

    To get around this, developers typically resort to lazy loading, a technique that comprises of sending a tiny temporary image with the initial payload (usually a blank pixel), which is then replaced when the real image, fetched asynchronously, has been downloaded and is ready to be used. In practice, this means that users don't have to wait for a large asset to be downloaded before they start seeing content on the screen, which is an improvement in perceived performance.

    Using a placeholder

    As an alternative to a blank pixel, we can use a placeholder generated from the original asset, as long as it's still small enough to have a marginal impact on the size of the initial payload. This creates a more pleasant visual effect, as users start seeing something that resembles the image they're expecting instead of just a blank slot.

    For example, we can take the original image and reduce its dimensions and compression quality, drastically bringing down the file size. To avoid getting a terribly pixelated image, we can add a blur effect to mask the imperfections.

    Here's how it looks like:

    Original image (203 KB)
    0_1508708466395_leaf-3.jpg

    100px wide placeholder (1 KB)
    0_1508708371357_leaf.jpg

    Placeholder stretched to 600px

    Using CDN recipes

    We could use CDN to generate a placeholder from any image using a set of URL parameters.

    https://cdn.somedomain.tech/samples/tree.jpg?width=120&quality=75&resizeStyle=aspectfit&blur=4

    A more convenient way is to use recipes (click here for a video where I talk about them). Just copy the following recipe file to your workspace directory.

    {
      "recipe": "placeholder",
      "settings": {
        "format": "jpg",
        "quality": "75",
        "width": "120",
        "resizeStyle": "aspectfit",
        "blur": 4
      }
    }
    

    And then you can generate a placeholder for any file by prepending its path with /placeholder , like https://cdn.somedomain.tech/placeholder/samples/leaf.jpg.

    Depending on how large your image slots are, you might want to adapt the recipe settings to better fit your needs. In particular, you can experiment with the width, quality and blur settings.

    Demos

    See the Pen DADI / CDN: Lazy loading a large image with a placeholder by Eduardo Bouças (@eduardoboucas) on CodePen.

    See the Pen DADI / CDN: Lazy loading images with placeholders by Eduardo Bouças (@eduardoboucas) on CodePen.


Log in to reply
 

Looks like your connection to DADI Forum was lost, please wait while we try to reconnect.