← Back toHTML DOM

Show a loading indicator when an iframe is being loaded

Written byPhuoc Nguyen
Level 2 — Intermediate
06 Apr, 2020
It's always a good practice to let user know what is happenning. This post demonstrates a common case where we show a loading indicator while an iframe is being loaded.
Here is our iframe:
<iframe id="frame"></iframe>

The markup

The loading indicator and iframe are organized as following:
<div class="container">
<!-- The loading indicator -->
<div class="loading" id="loading">Loading</div>

<!-- The iframe -->
<iframe id="frame" style="opacity: 0"></iframe>
Initially, the iframe will be hidden by setting the opacity to zero. On the other hand, the loading indicator could be displayed at the center and on top of the iframe.
We can apply some CSS styles to the container and loading elements:
.container {
/* To position the loading */
position: relative;

.loading {
/* Absolute position */
left: 0;
position: absolute;
top: 0;

/* Take full size */
height: 100%;
width: 100%;

/* Center */
align-items: center;
display: flex;
justify-content: center;
This page introduces the most simple way to center an element in both horizontal and vertical directions

Handle the event

The layout looks good now. By default, user will see only the loading indicator. We will hide the loading indicator (or even remove it if you want) as soon as the iframe is loaded:
// Query the elements
const iframeEle = document.getElementById('iframe');
const loadingEle = document.getElementById('loading');

iframeEle.addEventListener('load', function () {
// Hide the loading indicator
loadingEle.style.display = 'none';

// Bring the iframe back
iframeEle.style.opacity = 1;

See also

Questions? 🙋

Do you have any questions? Not just about this specific post, but about any topic in front-end development that you'd like to learn more about? If so, feel free to send me a message on Twitter or send me an email. You can find them at the bottom of this page.
I have a long list of upcoming posts, but your questions or ideas for the next one will be my top priority. Let's learn together! Sharing knowledge is the best way to grow 🥷.

Recent posts ⚡

Newsletter 🔔

If you're into front-end technologies and you want to see more of the content I'm creating, then you might want to consider subscribing to my newsletter.
By subscribing, you'll be the first to know about new articles, products, and exclusive promotions.
Don't worry, I won't spam you. And if you ever change your mind, you can unsubscribe at any time.
Phước Nguyễn