How to add a loader/ loading image to a website
Before getting into How to add a loader or a loading image to website, let’s know why it is needed. It sometimes happens that certain pages of a website take a while to load completely.
This is explained by a large quantity of “heavy” images or a mass of code to interpret. There are so many concepts that do not exist in the head of an average user who would come to visit your site.
The best way to inform him and not to risk losing visits is to use a “loader” (animation on loading). So that the visitor understands that the site is loading, and that it will appear soon.
I will explain, in 3 steps, how to add a loading image with jQuery.
Step 1: We must first insert the image into the html code page
- Either inserting one “div” and loading the image as a “background” using CSS.
- Either by inserting the image directly, via the “img” tag.
I prefer method # 1.
Step 2: Adding CSS to display the loader in a div
Adding CSS to display the loader in a div
.loader {
position : fixed;
z-index: 9999;
background : url('my-loader.gif') 50% 50% no-repeat;
top : 0px;
left : 0px;
height : 100%;
width : 100%;
cursor : wait;
}
This CSS code will force the loading image (my-loader.gif) to be placed in the center of the screen. You are free to customize your loading screen. It is for example possible to change the background color via the “background-color” property.
Step 3: We will add a fadeout effect using jQuery
Enter the code before the body closing tag:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(window).load(function() {
$(".loader").fadeOut("1000"); })
</script>
Button loader with jQuery, a simple and effective solution
Download the jQuery Button Loader plugin files
1. Load the Font Awesome file to call up the spinner icon.
<link rel="stylesheet" href="font-awesome.min.css">
2. Load the jQuery library and the jQuery Button Loader plugin.
<link href="buttonLoader.css" rel="stylesheet">
<script src="jquery-1.11.3.min.js"></script>
<script src="jquery.buttonLoader.js"></script>
3. Use JavaScript to call the animation at the click of the button.
$('.button-class').click(function () {
var btn = $(this);
$(btn).buttonLoader('start');
setTimeout(function () {
$(btn).buttonLoader('stop');
},
5000);
});