Display a loading icon until the page loads completely

Updated:
Isn’t it a great idea to show a cool animated image until your website is loading? Of Course, it will improve your site’s user experience.

Let’s learn how to use jQuery and CSS to show loading image while page loading. Free download loading gif images and use these 7 + 10 cool pre-loading icons.

Loading icon cube
Loading icon four square
Loading icon rubik's cube
Loading icon rectangle square dots
Loading icon tetris game
loading icon snake game
loading icon suffling rubik's cube
Loading icon rotating circles
loading icon fadein faceout circles
rotating two circles loader
Loading icon revolving circles
hangout loader icon
loading icon zoom in zoom out circles
Loading icon bouncing circle
loading icon kinetic rotation circle cross
google like loader
loading icon conectric circles fading out

Special Discount for SmallEnvelop Readers and Subscribers

Using my link, you will get 25% off on all InVideo plans
(Offer valid till 30th April)

Grab The Discount

Bonus: Canva is an excellent tool to design blog images, social banner, business cards, posters, infographics, resumes, and other visual graphics. It has a very user-friendly drag and drop interface that makes your job easy, so anyone can easily create beautiful graphics.
Canva also provides pre-made templates for posters, logos, cards, resumes, flyers, powerpoint presentations, and many more. It’s a wonderful tool that designers and non-designers both can use to create beautiful and appealing images.


How to show a Responsive loading icon or image while page loads.

1. Add a div just after <body> tag.

<div class="se-pre-con"></div>

2. Add some CSS to show the icon and bring it in the middle of the page.

/* Paste this css to your style sheet file or under head tag */
/* This only works with JavaScript, 
if it's not present, don't show loader */
.no-js #loader { display: none;  }
.js #loader { display: block; position: absolute; left: 100px; top: 0; }
.se-pre-con {
	position: fixed;
	left: 0px;
	top: 0px;
	width: 100%;
	height: 100%;
	z-index: 9999;
	background: url(https://smallenvelop.com/wp-content/uploads/2014/08/Preloader_11.gif) center no-repeat #fff;
}

3. Now add some jQuery to show the pre-loading icon when the page is loading and hide when it has finished loading.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.js"></script>

//paste this code under the head tag or in a separate js file.
	// Wait for window load
	$(window).load(function() {
		// Animate loader off screen
		$(".se-pre-con").fadeOut("slow");;
	});

All done, now reload your page and it will show a loading icon.

Many of you have been searching for a way to show a loading gif while actual image is being loaded or show a spinner gif while an HTML element or div is being loaded. Let’s learn how to show a loading icon over each image on your site while the image is loading, using jQuery.

How to show loading gif while actual image is loading – Very simple method.

Demo

1. Add the following script to < head >.

<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js'></script>
<script type='text/javascript' src='loadImg.js'></script>
<script type='text/javascript'>
    $(function(){
        $('img').imgPreload()
    })
</script>

The loadImg.js contains the plugin which will automatically detect the images on the page and hides it while the images are not loaded completely. Until then it will show a loading icon. You can change the ‘img’ to any div or class on which you want to show the spinner while it is loading.

The plugin loadImg.js contains the following code.

(function() {
  (function($) {
    return $.fn.imgPreload = function(options) {
      var delay_completion, i, image_stack, placeholder_stack, replace, settings, spinner_stack, src, x, _i, _len;
      settings = {
        fake_delay: 10,
        animation_duration: 1000,
        spinner_src: 'spinner.gif'
      };
      if (options) {
        $.extend(settings, options);
      }
      image_stack = [];
      placeholder_stack = [];
      spinner_stack = [];
      window.delay_completed = false;
      delay_completion = function() {
        var x, _i, _len, _results;
        window.delay_completed = true;
        _results = [];
        for (_i = 0, _len = image_stack.length; _i < _len; _i++) {
          x = image_stack[_i];
          _results.push($(x).attr('data-load-after-delay') === 'true' ? (replace(x), $(x).removeAttr('data-load-after-delay')) : void 0);
        }
        return _results;
      };
      setTimeout(delay_completion, settings.fake_delay);
      this.each(function() {
        var $image, $placeholder, $spinner_img, offset_left, offset_top;
        $image = $(this);
        offset_top = $image.offset().top;
        offset_left = $image.offset().left;
        $spinner_img = $('<img>');
        $placeholder = $('<img>').attr({
          src: 'data:image/gif;base64,R0lGODlhAQABA
                IABAP///wAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=='
        });
        $placeholder.attr({
          width: $image.attr('width')
        });
        $placeholder.attr({
          height: $image.attr('height')
        });
        spinner_stack.push($spinner_img);
        placeholder_stack.push($placeholder);
        image_stack.push($image.replaceWith($placeholder));
        $('body').append($spinner_img);
        $spinner_img.css({
          position: 'absolute'
        });
        $spinner_img.css('z-index', 9999);
        $spinner_img.load(function() {
          $(this).css({
            left: (offset_left + $placeholder.width() / 2) - $(this).width() / 2
          });
          return $(this).css({
            top: (offset_top + $placeholder.height() / 2) - $(this).height() / 2
          });
        });
        return $spinner_img.attr({
          src: settings.spinner_src
        });
      });
      i = 0;
      for (_i = 0, _len = image_stack.length; _i < _len; _i++) {
        x = image_stack[_i];
        x.attr({
          no: i++
        });
        src = x.attr('src');
        x.attr({
          src: ''
        });
        x.load(function() {
          if (window.delay_completed) {
            return replace(this);
          } else {
            return $(this).attr('data-load-after-delay', true);
          }
        });
        x.attr({
          src: src
        });
      }
      replace = function(image) {
        var $image, no_;
        $image = $(image);
        no_ = $image.attr('no');
        placeholder_stack[no_].replaceWith($image);
        spinner_stack[no_].fadeOut(settings.animation_duration / 2, function() {
          return $(this).remove();
        });
        return $image.fadeOut(0).fadeIn(settings.animation_duration);
      };
      return this;
    };
  })(jQuery);
}).call(this);

2. Add some markup having some images.

<div class="images">
	<ul>
		<li>
			<img class="main-img" src="https://smallenvelop.com/demo/image-loading/images/1.jpg">
		</li>	
		<li>
			<img class="main-img" src="https://smallenvelop.com/demo/image-loading/images/2.jpg">
		</li>	
	</ul>
</div>

3. Add some CSS code. Please make sure that the images have specific width and height so that the loading icon may be displayed in the center.

.images ul li img {
	width: 400px;
	height: 266px;
}
.images ul li {
	display: inline-block;
}

That’s all for the codes. You will able to show a loading icon over each image on the page while actual images are not fully loaded.

The final page would look like

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script type='text/javascript' src='loadImg.js'></script>
<script>
$(function(){
        $('img').imgPreload()
    })
</script>
</head>
<body>
<p><a href="smallenvelop.com/display-loading-icon-page-loads-completely/"><--Back to the Article.</a></p>
<h1>Display a Loading icon while images loads</h1>

<div>
	<div class="images">
		<ul>
			<li>
				<img class="main-img" src="https://smallenvelop.com/demo/image-loading/images/1.jpg">
			</li>
			
			<li>
				<img class="main-img" src="https://smallenvelop.com/demo/image-loading/images/2.jpg">
			</li>
			
			<li>
				<img class="main-img" src="https://smallenvelop.com/demo/image-loading/images/3.jpg">
			</li>
			
			<li>
				<img class="main-img" src="https://smallenvelop.com/demo/image-loading/images/4.jpg">
			</li>
			
			<li>
				<img class="main-img" src="https://smallenvelop.com/demo/image-loading/images/5.jpg">
			</li>
			
			<li>
				<img class="main-img" src="https://smallenvelop.com/demo/image-loading/images/6.jpg">
			</li>
		</ul>
	</div>
</div>


</body>
</html>

In the above demo, we have bundled 17 cool loading icons which you can use for your free and commercial project. If you want more icons just go to

This way we can show the loading image while your webpage is loading and while an image is completely loaded. I hope this simple preloader will help you improve your site’s user experience. If you get any difficulty using the codes to your website then do comment below. Feel free to contact me for any help.
Subscribe to our email list to get updates to this post.

143 thoughts on “Display a loading icon until the page loads completely”

  1. I’m liking this however I would probably use it sparingly. I’ve got a site that requires the page to be fully loaded before interaction can begin so this is spot on! Adding a loading icon for a basic content page might be a bit overkill though.

    Reply
  2. There is an issue with this. I have google ads on my site and those ads loads asynchronously.. But this loader shows till all page content loads including google ads and social plugins. After loading all plugin it went out and it shows that my site is slow…

    Reply
      • Tests whether a browser has JS turned on or off. Then creates .no-js or .js classes for you to use.

        Allows you to use the preloader script if js is detected or allows the user to still see the whole page if JS is not available. Otherwise non-js users would be stuck with a loading screen and could never see your content.

        Reply
        • What would be the name of this specific feature that we need ? Since on the website, we can build our own library including only the feature we need, to save on the library size obviously.

          Reply
    • Modernizr is an open-source JavaScript library that makes it easy for web designers to support different levels of experiences, based on the capabilities of the visitor’s browser. This allows designers to take full advantage of everything in HTML5 and CSS3 that is implemented in some browsers, without sacrificing control over the user experience in other browsers. Hope you get it.

      Reply
  3. Is there anyway to make this work inside a div? I.e., not to hide the whole page until loaded, but only to hide a certain div until the whole page has loaded?

    Reply
  4. A quick question Poonam, I have an image inside a div tag and modified the call to $(“#mydivid”).imgPreload()
    However, the image never shows up. I just see the spinner forever. Why do you think this is happening?
    Thanks for your reply.

    Reply
  5. is there a way to put the loading screen on a timer? some of the div on my page are still not fully loaded when the loading screen goes away so i want to hide that…

    Reply
    • if your images is in a resources folder append it as below. it should work.
      don’t forget the single quotation marks.
      background: url(‘../images/loader-64x/Preloader_2.gif’) center no-repeat #fff;

      put the js file in the body or a seperate js file while the js script link should be placed directly on top of the body closing tag

      i.e

      Reply
  6. Is it possible to have the icon display for a minimum amount of time for first time viewers? I have a client requesting an opening animation and my way around this would be to use a page loading gif but requiring it to run for 5 seconds or so for first time visitors and then to only display until page loads for all other visitors. Hope that makes sense.

    Reply
  7. Just the code that i was looking for, Thank you very much…

    what i want to-do with this is, apply the loading on a certain DIV while showing the header part of the website, just like what’s happening on the images, but the DIV has no images, is this possible?

    Reply
  8. Hi, I absolutely love these animations. I have very basic knowledge of coding and my question might sound silly. I wanted to know how these can be integrated on a wordpress website. I would like to add this to my site hoping it would help me reduce bounce rate http://activitydeck.com/

    Reply
  9. page loader.gif is not getting stopped even after page is fully loaded

    my css

    .container{position:relative;height:100%;width:100%;}
    .loader {
    position: fixed;
    left: 0px;
    top: 0px;
    width: 100%;
    height: 100%;
    z-index: 9999;
    background: url(‘fw/images/page-loader.gif’) 50% 50% no-repeat rgb(249,249,249);
    }

    my js

    $(window).load(function() {$(“.loader”).fadeOut(“slow”);})

    html

    Hope i did everything correct

    Reply
  10. hi. in my php i have this

    whilst in the error page.i have an image spinner.gif that i want to display whilst redirecting

    please help

    Reply
  11. Hello Everyone, How can I apply this to only the first time one visits the website? Instead of everytime one goes back to it? In other words, when the site is already on Cache.

    Reply
  12. //paste this code under the head tag or in a separate js file.

    // Wait for window load

    $(window).load(function() {

    $(“.site-content”).show();

    // Animate loader off screen

    $(“.se-pre-con”).fadeOut(“slow”);;

    });

    this code is continuosly buffering it’s not showing my website home page

    Reply
  13. Very helpful, but I want to use it for my wordpress website, Which file do i need to edit and put the above codes in order for loading gifs to work?

    Reply
  14. I’m using the version for when loading an icon or image and I’m getting the following error in the console: imgPreload is not a function

    This is happening even though the function exists in the loadImg.js and the html code is pointing to the correct directory where the file is saved.

    Does anyone have any suggestions on where I’m going wrong?

    Reply
      • hello poonam!!!!
        As you give the advice to Toni O. by replacing $ sign with jQuery he will solve his/her problem…i just want to know changing the $ sing to jQuery are depends either on the jQuery version or Browsers versions….

        Reply
    • Hello Midhun

      You can use http://loading.io/ for colored icons. You may find many icons very similar to the preloaders.net. You can apply custom colors and can download into SVG, CSS and gif formats. It’s a great website for custom preloaders.

      Thank you for visiting SmallEnvelop. Please subscribe to get updated with the latest post.

      Reply
  15. This is awesome! I tried it on my website, and it perfectly works (although I may need to use another gif images, since the ones you provided do not match my website’s color schemes).
    Thanks a lot for sharing this.

    Reply
  16. hello and thank you,
    i have a problem with this.
    when i’m using this code the jquery will throw this error in console :
    TypeError: a.indexOf is not a function[Learn More]
    but if i change the code to :
    $(document).ready(function(){…});
    it will work.
    is there any diffrent between them!?
    if yes and it should be as your code, what should i do!? tnx

    Reply
  17. hello poonam!!!!

    i just want to know, is the loading image working with the time or anything else….how the loading image get to know when it’s finish to load……what is the conceptual logic behind it……?????

    Reply
  18. Hello! Thanks for the amazing tutorial 🙂
    I’ve got one question…actually it’s not about code, but design. How are these GIFs made? By using Photoshop? I know that if I open the file in Photoshop it shows me the frames in the timeline, but I’ve always wondered how it’s the proccess of creation of these kind of animation. I see that each layer is enabled in its respective frame, but I’m curious to know a little more about it. Thanks in advance for the great information provided! 😀

    Reply
    • #Mafe if u will take a video and convert it into images you will find that the video is actually a big group of images clicked per mili second or even shorter. To make a GIF like that you just need to create a group of images clicked per second in the sequence you want your animation to work. Use Macromedia Flash MX or Adobe Flash to combine them (as presentation in PowerPoint) at particular time interval.

      Reply
  19. This loader is simply amazing. And it is working perfectly as described above. I’ve just two questions.

    1. How can I use for Ajax operations ?
    2. I want to make the body visible but in faded mode and loading image in front. How can I do that.

    Any help would be really appreciable.
    Thanks in advance.

    Reply
    • No, the jquery code is not compatible with jquery 3.x

      If you want to use it with 3.x you need to update the code like this:

      $(window).on(‘load’, function() {
      // Animate loader off screen
      $(“.se-pre-con”).fadeOut(“slow”);
      });

      Reply
  20. Hi Poonam,
    Tried in jsp as shown. It works beautifully.

    Iam trying to do in JSF.Any thing extra need to be done at JSF(xhtml) as it is not loading. One more thing how to add background: url(images/loader-64x/Preloader_2.gif) in css page in JSF project and also how to include javascript and css in Xhtml .(Any difference from jsp pages which is shown ) It is not loading.

    Kindly help me.

    Reply
  21. I can’t seem to get this to work. Could you explain exactly where I put each bit of code?

    I am using Divi with a child theme. I put the first code in the ‘after body tag’ section in the Divi settings. I then put the CSS in the style.css in the child theme and lastly when I put the jQuery in the child functions.php file the website broke. I tried it in the head tag too, but it still didn’t work. Do you know what I am doing wrong? Thanks

    Reply
  22. Work really great, but i don’t get why is this in your code:

    .no-js #loader { display: none; }
    .js #loader { display: block; position: absolute; left: 100px; top: 0; }

    Reply
  23. Hello,
    on your first loading, I just write this and it’s work.
    In my case, I want a loading only on somme button so …

    You need a fadeIn and a fadeOut in your js
    and a display:none in .se-pre-con.
    I suppress your .no-js #loader and .js #loader (why this code, I don’t understand)

    For CSS :
    .se-pre-con {
    position: fixed;
    left: 0px;
    top: 0px;
    width: 100%;
    height: 100%;
    z-index: 9999;
    background: url(“../../../medias/logo/mygifname.gif”) center no-repeat rgba(255,255,255,0.8);
    display: none;
    }
    transparence on the background is more user friendly

    JS :
    //In my function > + or – button cart :
    $(document).ready(function () {
    $(“.se-pre-con”).fadeIn(“slow”);
    });

    //In my success function cart :

    function refreshCartContentPage() {
    $.ajax({


    $(“.se-pre-con”).fadeOut(“slow”);

    }
    });
    }

    Enjoy

    Reply
  24. If anyone is having problems with their page not loading when using the window.onload event it is because of as jQuery 3.0 it is deprecated and no longer exists. What you should do is bind the on method to the load event like so:

    $(window).on(‘load’, function() {
    // Animate loader off screen
    $(‘.se-pre-con’).fadeOut(‘slow’);
    });

    I think it is better to use window.onload vs document.ready as window.onload waits for all the images to be rendered as well as the content whereas i believe document.ready simply waits for the content to be loaded but i guess it depends on what you prefer. 🙂

    Reply
  25. how can i attach loading image from local machine?
    I tried below way..bit it didnot work

    Kindly help anyone.

    Thank you

    #load{
    width:100%;
    height:100%;
    position:fixed;
    z-index:9999;
    background: url(‘D:\Notes_jaya\Issues\loading.gif’) repeat center center rgba(0,0,0,0.25)
    }

    JavaScript Progress Bar

    document.onreadystatechange = function () {
    var state = document.readyState
    if (state == ‘complete’) {
    setTimeout(function(){
    document.getElementById(‘interactive’);
    document.getElementById(‘load’).style.visibility=”hidden”;
    },1000);
    }
    }

    Reply
  26. Hello,
    Do you know why the first script would stop images (profile icons) being displayed in Elgg?
    Could the javascript be interfering with other javascript in the site? Or is it something else? There is also a white border around the site as if the script has put the page in an iframe.

    Reply
  27. the method is deprecated

    use this

    $(window).on(‘load’, function() {
    $(“.se-pre-con”).fadeOut(“slow”);;
    });

    Reply
  28. An awesome article. I hope to be able use this trick at some point.
    By the way, the demo used in the article, https://smallenvelop.com/demo/image-loading/,
    doesn`t seem to work; maybe the images load to fast, though 1 appears to be gone from the media library & gets a 404 message when I check the image link, or maybe that was intentional, so that it could never load, in which case then, no GIF image appears any where on the page.
    I was able to see a demonstration thanks to Leekid`s Comment made onDecember 3, 2016 at 5:44 pm,
    “Works perfectly on my radiocapsule.com website. Thanks for the method sharing”, at:
    http://radiocapsule.com/
    He doesn`t use one of the provided GIFs though, but instead uses a custom GIF that appears to an animated radiowave aimed downward. Pretty cool Leekid.
    Thanks for the “How-To” article, Poonam

    Reply
  29. Hello!!

    Your tutorial is awesome, honestly. But I have a tiny problem, is that the loading keeps going… I don’t know if you would know how to fix that? Thank you!!!

    Have a lovely day

    Reply
  30. I tried with this code a lot but the image presisted each time. It gave me a tough time. Then my friend suggested me to put the code:
    $(window).load(function() {
    // Animate loader off screen
    $(“.se-pre-con”).fadeOut(“slow”);;
    });

    at the bottom of the page even after the tag and it worked. Try this it might work for you.

    Reply
    • I used jquery 3x, For some funny reason, FadeOut isnt working. I edited the code to this:

      $(window).on(“load”, function() {
      $(“.se-pre-con”).hide();
      });

      Reply
  31. This is how i got mine to work.
    Just adjust the img/pre.gif to change the loader

    Basically just changed the jquery line.

    $(window).load(function() {
    $(“.se-pre-con”).fadeOut(“slow”);
    });

    .no-js #loader { display: none; }
    .js #loader { display: block; position: absolute; left: 100px; top: 0; }
    .se-pre-con {
    position: fixed;
    left: 0px;
    top: 0px;
    width: 100%;
    height: 100%;
    z-index: 9999;
    background: url(img/pre.gif) center no-repeat #fff;
    }

    Reply
  32. Thank you so much for this! Super easy to follow and helped me learn how to tweak it to my own liking 🙂 I really appreciate it!

    Reply
  33. can you plz help me out because that animation is not stopping at all and my web page is not loading. I’m not using this code to load images, i want this animation to before my page loads. Thanks

    Reply
  34. Be careful using jquery window load function. This will wait until ALL resources have finished loading which means if anything is slow or stuch the user will be stuck at the preloading screen. Better UX would be to abort after X amount of time.

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.