DEV Community

Jen C.
Jen C.

Posted on • Edited on

Optimize Core Web Vitals - FCP and LCP: Lazy-Loading Offscreen <iframe>

Pre-study

It's time to lazy-load offscreen iframes!

display: none

iframe#lazy

An example page with an OpenStreetMap <iframe>

To ensure the <iframe> loads only when the user clicks the button, it is initially hidden using the inline style style="display: none".

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <title>title</title>
    </head>
    <body>
        <main>
            <header>
                <h1>Welcome to HTML Test Content</h1>
                <p>A simple example for practicing HTML and CSS</p>
            </header>

            <article>
                <h2>About This Page</h2>
                <p>
                    This page contains various HTML elements to help you test
                    and practice.
                </p>
                <ul>
                    <li>Text formatting</li>
                    <li>Images and links</li>
                    <li>Tables and lists</li>
                    <li>Forms and inputs</li>
                </ul>
            </article>

            <button
                onclick="document.getElementById('inlineFrameExample').style.display = 'block';"
            >
                Show Map
            </button>

            <iframe
                style="display: none"
                id="inlineFrameExample"
                title="Inline Frame Example"
                width="600"
                height="400"
                src="https://www.openstreetmap.org/export/embed.html?bbox=-74.0479%2C40.6799%2C-73.9067%2C40.882&layer=mapnik"
            >
            </iframe>
        </main>
    </body>
</html>
Enter fullscreen mode Exit fullscreen mode

However, when inspecting the page, we can see that the contentDocument of the <iframe> is fully loaded even before any user interaction, as shown in the image below:

Image description

To prevent unnecessary resource loading before user interaction, add the attribute loading="lazy" to the <iframe>.

...

<iframe
    loading="lazy"
    style="display: none"
    id="inlineFrameExample"
    title="Inline Frame Example"
    width="600"
    height="400"
    src="https://www.openstreetmap.org/export/embed.html?bbox=-74.0479%2C40.6799%2C-73.9067%2C40.882&layer=mapnik" >
</iframe>

...
Enter fullscreen mode Exit fullscreen mode

When inspecting the page, we notice that the <iframe> element has an empty contentDocument before the user interacts with it.

Image description

Additionally, when we check the Network tab, we can see that the resources for the <iframe> are not loaded before the user clicks the button.

Image description

After clicking the button, the resources for the <iframe> are successfully loaded:

Image description

Feel free to follow me on GitHub 🎉

Top comments (0)