How to lazy load iframes?

By Gulshan Saini
Published in Browser
July 18, 2020
1 min read

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.

What caused the performance issue?

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

performance issue before lazy loading iframe
performance issue before lazy loading iframe

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

performance issue fixed after lazy loading iframe
performance issue fixed after lazy loading iframe

If we compare before and after screenshots, we can see the following differences

No. of requests5239
Data transfered886kB582kB
Resource downloaded2.7 MB1.5 MB
Time to load4.4s4.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.


Previous Article
How to create a React component?

Related Posts

How to launch Chrome browser from command line?
September 10, 2020
1 min
Gulshan Saini

Gulshan Saini

Fullstack Developer



Subscribe to our newsletter!

We'll send you the best of our blog just once a month. We promise.

Quick Links

Contact UsBrowserCSSPythonPuppeteer

Social Media