Imagine a situation in which you enter a new site. The content you are desperately searching for doesn’t seem to be loading. You don’t know whether something is actually loading, or if it is just not there. You finally decide to exit the page.
This situation can be very typical when websites generally need large files to be downloaded. In order to combat such a situation, a load icon may be used to signify that something is loading.
In this simple tutorial, I will take you through the usage of one of these icons in your own website.
To begin, obtain a simple ajax-loader.gif image from AjaxLoad.info. This image will be the basis in which to create the loading effect. For this tutorial, I will use the default image.
Now, let’s create a simple HTML file with two images:
<img id="loader" src="ajax-loader.gif" alt="Loading, Loading!"></img>
<img id="large-img" src="https://server.flowoflogic.com/gd.php" alt="London Eye"></img>
#loader
signifies the load icon and #large-img
is a large image which will take a bit of time to load.
We may now import jQuery:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
The routine we need to create in jQuery has a clear structure:
- Hide the
#large-img
so it loads in the background. - When the image has finished loading, hide the load icon.
- Display the image.
Here is the resulting code:
$(function() {
$('#large-img').hide();
$('#large-img').load( function() {
$('#loader').hide();
$('#large-img').show();
} );
});
For those of you who don’t want an extra 19 KB from jQuery, use the following:
var largeImg = document.getElementById('large-img');
largeImg.style.display = 'none';
largeImg.onload = function() {
document.getElementById('loader').style.display = 'none';
largeImg.style.display = 'block';
}
Good luck!