If you are including iframe
elements in your HTML pages, you may want to consider displaying a simple “loading” indicator to let your end users know that content is being loaded within the iframe
instead of just displaying
empty space.
There are many ways to accomplish this. In this tutorial, we are going to look at one of the ways to do this using jQuery. This tutorial simply covers how to display an animated image while loading the iframe
content.
Example
In the code below we have included the HTML, CSS, and JavaScript/jQuery in the same page. Of course, in practice, we would separate the CSS into its own style sheet as well as move the JavaScript/jQuery code to its own external file.
In the example below, all we are doing is immediately displaying the animated GIF in the middle of the iframe
element. Once the iframe
content completes the loads, the hideLoader()
function is executed via the onload event on the iframe
element. The JavaScript function then simply changes the display style property for the animated GIF to “none” which essentially hides the image.
<!DOCTYPE html>
<html>
<head>
<title>jQuery Demo - IFRAME Loader</title>
<style>
#frameWrap {
position:relative;
height: 360px;
width: 640px;
border: 1px solid #777777;
background:#f0f0f0;
box-shadow:0px 0px 10px #777777;
}
#iframe1 {
height: 360px;
width: 640px;
margin:0;
padding:0;
border:0;
}
#loader1 {
position:absolute;
left:40%;
top:35%;
border-radius:20px;
padding:25px;
border:1px solid #777777;
background:#ffffff;
box-shadow:0px 0px 10px #777777;
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
</head>
<body>
<div id="frameWrap">
<img id="loader1" src="loading.gif" width="36" height="36" alt="loading gif"/>
<iframe id="iframe1" src="targetPage.html" ></iframe>
</div>
<script>
$(document).ready(function () {
$('#iframe1').on('load', function () {
$('#loader1').hide();
});
});
</script>
</body>
</html>