Question

I have a loading gif that I have appearing on the screen when someone comes to my page. It looks like this:

<style type="text/css">
    #dvLoading
    {
        background: url(../images/loader.gif) no-repeat center center;
        height: 100px;
        width: 100px;
        position: fixed;
        z-index: 1000;
        left: 50%;
        top: 50%;
        margin: -25px 0 0 -25px;
    }
</style>

and my javascript that shows this looks like this:

<script class="code" language="javascript" type="text/javascript">

    $(window).load(function () {
        $('#dvLoading').fadeOut(2000);
    });
</script>

However, it seems as though the page loads and then the loading gif briefly appears. Is there a better event other than .load that will do the job for me?

Was it helpful?

Solution 2

So perhaps your problem is that your script to hide the gif starts running before the image is actually loaded.

Rather than loading the image with css, you could load it dynamically on document load and set your fadeOut to fire on image load.

js:

var $img = $('<img>', {
               src: '../images/loader.gif',
                id: 'dvLoading'
              }).load(function() {
                 $(this).fadeOut(2000);
              });

UPDATE

forgot to attach your image. of course this could be to any element you choose

$('body').append($img);

OTHER TIPS

You wont be able to achieve this effect the way you are doing it. Because your styles and your javascript loads with the page, so by the time you display your loading animation everything is already loaded. The only way you can achieve your goal is to load empty html shell with your loading indicator and javascript that will request the rest of the html through async ($.ajax) request, this way you can show your loading indicator once async request is issued to get html and hide it when async request is done.

the event you are using is correct as load is called after all resources are loaded including images css etc.

To make gif appear, instantaneously, before other images load in the page, try and load the gif at the start of body. Also, you can host the gif in a CDN for faster availability.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top