Lazy Loading: Why We Implement It And How Its Done

Written by Matt on 10th October 2017

So what is Lazy Loading?

Lazy Loading is a phrase used to describe the functionality that loads content into a page when you have scrolled all the way to the bottom, this can also be known as infinite scrolling. We call this lazy because the server is only serving a selection of content on the initial page load before any interaction have taken place. By being lazy, the website only needs to get 20 or so products on its initial load, instead of fetching all 4000 that may be available. This means that the server performs less queries and loads the page into your browser much faster.

A benefit of lazy loading is that with a smaller dataset, it can now be cached more efficiently. Most optimised sites take advantage of caching in some form today, this reduces the number of queries on a page and improves the load speed, it does this by fetching the cached data with a single query instead of processing all of the code and compiling it each time. However, these caches can become very large if there is too much content and you can end up with errors preventing the page from loading. By using caching with the lazy loaded segments, the initial load is not only quicker, but the rest of the content will load much faster too.

The initial page load speed isn't the only thing affected by lazy loading though, as it also has a big impact on the size of the page. A smaller page will take less time to fully download onto a mobile device and also take up less of a visitors data allowance, this is because they are only downloading for example 400kb instead of 1.2mb. When dealing with a slow mobile connection, a lightweight page can load much faster and as a result is less likely to test the persons patience which should lead to lower bounce rates as a result. When a page takes too long to load it becomes more likely that a visitor will get frustrated and just hit the back button to try a different site instead of waiting for the page to respond.

Does Lazy Loading really make a difference?

In the image below, you will see a speed test comparison that compares the same page before and after implementing lazy loading. This has resulted in a reduced page load speed by 4.7 seconds! This test was however run from Canada though and the site we tested is hosted in the UK. This means that we could expect to see a lower load time on both sides of the test when connecting to the site from the UK. Keeping this in mind though, it is still a significant improvement.

The page size has also decreased by 783 kilobytes which is a substancial drop. This has been achieved mostly by loading in less images on the page thanks to the lazy loading functionality. We are also making 122 less requests, which helps the page to load quicker. Most of these requests will be for the images we are no longer loading on our initial page. For each request made, the server runs through a number of processes to generate that data or recieve it and then return it to the page, by reducing the number of requests we can lighten the load on the server so that it can serve us our content quicker.

Although the load times are still rather high, this is because of the location the test was made from and we can see significant gains across the board. We do have a number of different testing tools we could use and further pagespeed optimisations that we could make to the site but this is a substancial improvement. A slow loading page causes frustration for site visitors because people are used to having pages load quickly in this day and age. It is important to keep on top of your pagespeed as it is a ranking factor in googles search ranking algorithms, and also more importantly an irritation for visitors. A well designed site should be easy to use and fast to load, if it fails on either of these counts then you will lose traffic due to frustrated visitors.

Lazy Loading Simple Product Filtering

Lazy Loading benefits on a product list

How can we implement Lazy Loading?

The first step is a familiar one for developers, we need to add pagination to our page. This may seem a little odd to begin with because when we set up pagination we are usually intending to show our content across multiple pages. Pagination is necessary in this case though as it will target the correct elements when you make the request to load the next set of content (or second page) at the bottom of the page.

What we are essentially doing is hiding our next and previous pagination links and then triggering some javascript when we reach them in the browser, this replaces the links with the content of our next page. So instead of clicking to go to page 2, we load the items from page 2 and append them to the document. This allows us to perform our caching across our pagination in the traditional way we would in our environment. We also remove the need to reload the static elements of our page though such as the header, the footer, and the sidebars. These elements all stay consistant throughout our pagination so they are not needed, this means that we can tailor our ajax request to target only the containing element which holds all of our new items and then append them to the page.

Lazy Loading Advanced Product Filtering

Advanced category filtering combined with Lazy Loading

You will see in the image above that we have some advanced category filtering with checkboxes. This means that you can select multiple filters and match on any product that has at least one attribute from each of the groups e.g. colour, size, etc.

This was a tricky one to convert to lazy loading but it can be possible with the correct cache keys and some complicated code. If you can get it working with regular pagination then it is an easy jump to lazy loading. There are many libraries out there that will enable lazy loading. We have used http://imakewebthings.com/wayp... but we recommend that you try out a couple until you settle upon one you feel comfortable with.

if ($('.infinite-more-link').length) {
	$('.infinite-more-link').hide();
	var infinite = new Waypoint.Infinite({
		element: $('#container')[0]
	});
}
if ($('.infinite-less-link').length) {
	$('.infinite-less-link').hide();
}
$("input[name='categoryFilter[]']").change(function() {
	window.history.replaceState({}, null, url);
	$("#container").load(url+" #container .product", function() {
		$("#paginateLinks").load(url+" #paginateLinks a", function(){
			infinite = new Waypoint.Infinite({
				element: $("#container")[0]
			});
		});
	});
});

The above code block is an example of how we have loaded in our additional products when the category filtering is changed. I have left some parts out because I wanted to show only the lazy loading sections where we have used the waypoints library to initialise our infinite scrolling. When our filtering is updated, to show our new results we have chosen to update our url first so that refreshing the page will retain the filtering criteria and it can be bookmarked or shared. Next we load in our newly filtered list of initial products using ajax from our first page. After this is done, we need to update our pagination link urls so that lazy loading will fire correctly. Finally we need to update our infinite variable which we set at the start of the code block so that the lazy laoding will fire correctly when triggered.