Vignesh Hariharan
Published on

Why and how behind lazy load in web performance

Why and how behind lazy load in web performance

Almost every blog post that I have read suggests one technique to improve page load speed which is "Lazy loading".

Why is it a recommendation? Let's just say a user is browsing the web at 12Mbps speed on a mobile internet connection which means that it will take a second to download the resource with a size of 1500kb.

This is only the download speed, there is also DNS time, and TCP connection time and if the resource is a javascript file, there is also the parsing and compilation time to be considered.

As a result, it makes sense to load only the files required. If you feel the app you are working on needs some improvement in page load speed, here are some of my learnings and what I would do if I were to improve page load speed.

Measuring and Analysing

Measure the page load speed with web vitals metrics for your app, it can be lab data or directly from your users. I think the best way would be to get real users' data how on your app is performing on real users, You might wanna read about it more from this CRUX or you can check whether you already have it at pagespeed.

After you have hands-on these data, it would be good to take the median value of the metrics you are measuring like web vitals instead of the average. Since the median gives a realistic view of the data collected.

To lazy load, the resources, learning about the priority and sizes of the resources you need to use will help in giving you an idea of how much data needs to be in the initial load of the application which will help you make correct decisions.

For example, if your users are visiting the app from mobile, it makes sense to load content that is only shown in the first fold of the app. You can use this tool to set a budget for page load speed. performancebudget

Lazy load - javascript

When you are loading a client-side rendered react app it takes time to download react, react-dom, and the application code in a single bundle file.

You can make use of code splitting to break down the resources and load them only when necessary to reduce the time to download these resources. Code splitting in Webpack can be implemented by :

  • Using dynamic import in javascript files. Webpack will split the modules when these files are built by default.
  • Using the entry option in the Webpack config will split the files according to the configuration you provide.
  • Using Split Chunks Plugin.

Lazy load - images

You can lazy load them with the loading="lazy" attribute in images or with intersection observers. Tools:

References