In this tutorial, I am going to show you how I improved website performance by just adding attribute loading="lazy"
to iframes. Tutorial.tips is built on GatsbyJS, a blazing fast static site generator. I never thought that website is going to have any performance issues since I was using GatsbyJS however, I was wrong as my assumption ignored other factors that might impact performance.
Recently I posted a tutorial on How to create a React component? After posting the tutorial I thought to check the website performance using lighthouse. To my surprise, lighthouse indicated performance issues, due to unused JavaScript calls and the content loaded by those network calls was higher than optimal limits.
For tutorials.tips demos, I usually host on CodePen. To embed CodePen demos, I created a common component that embeds the iframe with unique CodePen id. To run the demos, CodePen also sends additional JavaScript to the client, which is lightweight and compressed however, anything extra will cause performance issues. The second thing was the demo itself which, included the import of React, ReactDOM, and Babel library which loads another 1.2 MB of resources approximately.
Below is screenshot network calls and DOMContent loaded before the issue was fixed
To fix the issue I, added loading="lazy"
to the iframe element. Since I was using a common component for CodePen it was easy to fix the issue across the site with a small change in component code.
The loading attribute on an
<img>
element (or the loading attribute on an<iframe>
) can be used to instruct the browser to defer loading of images/iframes that are off-screen until the user scrolls near them.
Once the fix was deployed I was able to save approximately 1.2 MB of network resources and I see improvement in lighthouse score as well.
Following screenshot was taken after the issue was fixed
If we compare before and after screenshots, we can see the following differences
Parameter | Before | After |
---|---|---|
No. of requests | 52 | 39 |
Data transfered | 886kB | 582kB |
Resource downloaded | 2.7 MB | 1.5 MB |
Time to load | 4.4s | 4.1s |
Even after the fix, I see a lot of room for improvement, which could be achieved by optimizing images and also load them lazily.