Show a loading indicator when an iframe is being loaded
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">
<div class="loading" id="loading">Loading</div>
<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:
.container {
position: relative;
}
.loading {
left: 0;
position: absolute;
top: 0;
height: 100%;
width: 100%;
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:
const iframeEle = document.getElementById('iframe');
const loadingEle = document.getElementById('loading');
iframeEle.addEventListener('load', function () {
loadingEle.style.display = 'none';
iframeEle.style.opacity = 1;
});
See also