Lazy Loading for Images… So Easy

How to defer loading for increased performance

Nicholas Cunningham
3 min readJan 27, 2019

This is a pretty quick post about Angular directives and how to use some new browser APIs to achieve them.

These can also can be used outside of Angular. The code isn’t too attached to a framework because the underlying functionality is really just JavaScript.

In this current environment, applications need to load fast and have many assets (images, fonts, translations, etc.). Performance is on everyone’s mind, or at least most people’s.

One technique to achieve this is to use lazy loading.

Lazy loading is a technique that defers the loading of non-critical resources while the page is initially loading. Instead, these non-critical resources are loaded at the moment of need. Where images are concerned, “non-critical” is often synonymous with “off-screen.”

In a much simpler form, it allows you to load resources that are not needed until necessary or at a point in time where the application is idle.

Let’s say we have 500 images (an exaggeration). So, items is an array of length 500. If each image is 1mb in size (another exaggeration)️, we would hypothetically load 500mb worth of data, even though the user will see four to five at a time, at most.

The Solution

One way to deal with this problem is to use the Intersection Observer API.

The Intersection Observer API provides a way to asynchronously observe changes in the intersection of a target element with an ancestor element or with a top-level document’s viewport.

This just means that it provides a way to allow developers to know when an element is currently being viewed (can be seen).

One way to allow this to be shared, but modular, is to create a directive:

All this does is create an intersection observer on the element. Then we utilize the entry.isIntersecting property, which does a lot of the heavy lifting. It’s created this way for brevity. Read more about the API in the previous link.

Then, let's add the directive into our image element:

After using the directive

As you can see, the image that is currently being shown has an src attribute, but the one below it doesn’t. If we scroll it into view, the intersection object will notify the directive and the directive will apply the src to it.

And that’s it! Easy.

The package is available on npm.

--

--