What I have done below is a simplified method for the iframe
waiting to be loaded, and meanwhile in the background a gif is shown. When the iframe
is completely loaded, the gif disappears. Be aware that this is specific for jQuery.
I have removed the <img>
of your code, this won't work. I have simplified it by adding a class to div#printdiv
called load-gif
and gave it background
styling.
I have also added an opacity function. Otherwise you see a page being loaded in the iframe while the gif is still in the background. To avoid this iframe
is invisible (opacity: 0;
) until it's fully loaded and then opacity turns back to opacity: 1;
.
body {
height: 40vw;
width: 100%;
background-color: #e4e4e4;
}
#printdiv {
display: flex;
align-items: center;
justify-content: center;
border: 1px solid #e4e4e4;
height: 100%;
margin: 3em;
}
#printdiv>p,
body>div,
#frame1 {
width: 100%;
height: 100%;
}
#printdiv,
#frame1 {
background-color: white;
}
/* Below CSS are the important factors, above is just example styling. */
#frame1 {
opacity: 0; /* set at 0 to avoid gif and iframe mixture in the same div */
}
.load-gif { /* extra class to load gif */
background: url(https://loading.io/assets/img/ajax.gif) center no-repeat;
background-size: contain;
}
<!-- begin snippet: js hide: false console: true babel: false -->
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
jQuery(document).ready(function() { // starts DOM page is ready
jQuery("#frame1").on("load", function() { // when iframe is completely loaded
jQuery(".load-gif").css("background", "unset"); // removes gif
jQuery(this).css("opacity", "1"); // set opacity to normal value
});
});
</script>
</head>
<body>
<div>
<div id="printdiv" class="load-gif">
<p>
<iframe id="frame1" src="/" frameborder="0"></iframe>
</p>
</div>
</div>
</body>
</html>
An alternative way is to remove the load-gif
class completely after iframe
is loaded. jQuery will look like this:
jQuery(document).ready(function() { // starts DOM page is ready
jQuery("#frame1").on("load", function() { // when iframe is completely loaded
jQuery('#printdiv').removeClass("load-gif"); // removes gif class
jQuery(this).css("opacity", "1"); // set opacity to normal value
});
});