← Back toHTML DOM

Show a loading indicator when an iframe is being loaded

Written byPhuoc Nguyen
Created
06 Apr, 2020
Category
Level 2 — Intermediate
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:
html
<iframe id="frame"></iframe>

The markup

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

<!-- The iframe -->
<iframe id="frame" style="opacity: 0"></iframe>
</div>
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:
css
.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;
}
Resource
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:
js
// 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

If you found this post helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks 😍. Your support would mean a lot to me!

Questions? 🙋

Do you have any questions about front-end development? If so, feel free to create a new issue on GitHub using the button below. I'm happy to help with any topic you'd like to learn more about, even beyond what's covered in this post.
While I have a long list of upcoming topics, I'm always eager to prioritize your questions and ideas for future content. Let's learn and grow together! Sharing knowledge is the best way to elevate ourselves 🥷.
Ask me questions

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