Use an animated gif on long running post backs

With all the new jQuery and client callback methods available to .net developers, it has become a lot easier to refresh the DOM of a running page without a reload. However, sometimes you just want to display an animated gif after the user clicks a button until the page reloads, in order to display some sort of visual indication to the user that something is happening.

This is not as easy as it sounds and I think I tried 5-6 options before I found a good solution.

So in this case I am importing pages to EPiServer from a sitemap XML. I was importing 820 pages and it took too much time so I needed to display some kind of animation to show that the import still was in progress.

So we have our html code. When the user clicks the btnImport we start to import the pages from the sitemap.

<div class="epi-buttonContainer">
    <span class="epi-cmsButton">
        <asp:Button ID="btnImport" 
           runat="server" 
           CssClass="epi-cmsButton-text epi-cmsButton-tools epi-cmsButton-Import" 
           Text="Import" 
           OnClick="btnImport_Click" 
           OnClientClick="showLoading();" />
    </span>
    <div id="loading" style="float: left; visibility:hidden;">
        <img src="../../Img/loading.gif" alt="" />
    </div>
</div>

We have our div containing the animation. By default we set the visibility to hidden and when the user clicks the button we use the OnClientClick event to call the javascript function showLoading(); to display the div before postback.

<script type="text/javascript">
        function showLoading() {
            setTimeout("document.getElementById('loading').style.visibility = 'visible'", 200); 
        }
</script>

As you can see we are just using ordinary JavaScript to change the visibility of the div, but we are calling the function via JavaScript setTimeout function. If we don't use the setTimeout the gif animation will just freeze, but if we set a little 200 ms wait on the function the animation will be loaded correctly. Once the post back is ready and the page is reloaded the animation will be hidden again.

This is a really easy way to display an animated gif on post back without including jQuery or another typ of AJAX.