How to display loading dialog when someone clicks a specific link?

52,604

Solution 1

You can do this :

$(function(){
​  $('a').click(function(){
     $('<div class=loadingDiv>loading...</div>').prependTo(document.body); 
  });​
});

Demonstration (change the link to a very slow page for best effect)

But it depends on the page : if the page sends immediately some content but not the whole content, you won't have the time to see your div.

Solution 2

If you also need an animation, it becomes a complicated matter as browsers behave very differently. Some stop all GIF animations when a new page starts loading. Basically it comes down to something like this if you have jQuery and download the spin.js library.

See working solution here:

http://jsfiddle.net/7aJyP/

<style>
#loading {
    display:none;
    position:absolute;
    left:0;
    top:0;
    z-index:1000;
    width:100%;
    height:100%;
    min-height:100%;
    background:#000;
    opacity:0.8;
    text-align:center;
    color:#fff;
}

#loading_anim {
    position:absolute;
    left:50%;
    top:50%;
    z-index:1010;
}
</style>



<div id="loading"><div id="loading_anim"></div></div>

<a href="http://pangoo.it" class="mylinkclass withanimation">link</a>



<script>

$(function () {
    $(".withanimation").click(function(e) {
        e.preventDefault();
        $("#loading").show();

        var url=$(this).attr("href");

        setTimeout(function() {
            setTimeout(function() {showSpinner();},30);
            window.location=url;
        },0);

   });
});

function showSpinner() {
    var opts = {
      lines: 15, // The number of lines to draw
      length: 3, // The length of each line
      width: 4, // The line thickness
      radius: 30, // The radius of the inner circle
      rotate: 0, // The rotation offset
      color: '#fff', // #rgb or #rrggbb
      speed: 2, // Rounds per second
      trail: 70, // Afterglow percentage
      shadow: false, // Whether to render a shadow
      hwaccel: false, // Whether to use hardware acceleration
      className: 'spinner', // The CSS class to assign to the spinner
      zIndex: 2e9, // The z-index (defaults to 2000000000)
      top: 'auto', // Top position relative to parent in px
      left: 'auto' // Left position relative to parent in px
    };
    $('#loading_anim').each(function() {
        spinner = new Spinner(opts).spin(this);
    });
}
</script>

If you use an animated (GIF) the animation may freeze on some browsers. I used spin.js library ( http://fgnass.github.com/spin.js/ ). While GIFs get frozen the javascript animation seems to be working.

Please test with ALL browsers!

Solution 3

Although ajax would be more elegant, it's possible. You have to intercept the navigation by preventing the default event, then force an update to the UI, then change the location to the destination url. Something like this:

$('#mylink').click(function(e) {
    e.preventDefault();
    var url = this.href;
    // Update the UI here
    setTimeout(function() {
        // This is a trick to force a repaint
        window.location.href = url;
    },0);
});

Solution 4

This is an old topic, but if you want a simple solution that doesn't depend on JQuery add the following to onClick in your link:

<A href="http://veryslowload.com" onClick=""javascript:document.getElementById('page-loader').style.display='block';"">slow load...</a>

Then somewhere on your page, have a hidden DIV that includes what you want for the loading dialog.

<div id="page-loader">
  <h3>Loading page...</h3>
</div>

and hide the DIV with CSS as follows:

#page-loader {                                                                                                     
  position: absolute;                                                                                              
  top: 0;                                                                                                          
  bottom: 0;                                                                                                       
  left: 0;                                                                                                         
  right: 0;                                                                                                        
  z-index: 10000;                                                                                                  
  display: none;                                                                                                   
  text-align: center;                                                                                              
  width: 100%;                                                                                                     
  padding-top: 25px;                                                                                               
  background-color: rgba(255, 255, 255, 0.7);                                                                      
}

Here's a JSfiddle to a working example: http://jsfiddle.net/meb69vqd/

I can't take full credit for this example. There are additional tips about this technique here: https://css-tricks.com/css-page-loader/

Solution 5

Presumably, you'll want the loading dialog to appear immediately, then to disappear and be replaced by the new page when the new page has rendered?

Three ideas come to mind.


If you have control of the source page but not the target - Use a click event handler to replace the tags' normal behavior with something like this:

  1. Display the loading animation
  2. Fire an AJAX request to the URL defined by the tag's href attribute (alternately, create a hidden with the URL as its source)
  3. When the request has completed, replace the document's contents with the response.

This can get really hairy, though, since you won't lose javascript and css defined in the original page. It also won't change the URL displayed in the user's browser.


If you have control of the target and can make the target cacheable (even for a few seconds): You could load the page in the background via AJAX and then redirect to it. The first load will be slow, then the redirect will load the page from cache.


And yet another alternative: If you have control of the target page, you can define an optional parameter such that if the parameter is present, the server returns a page consisting of only the loading animation and a bit of javascript that loads the actual page.

Share:
52,604
sorin
Author by

sorin

Another geek still trying to decipher the meaning of “42”. It seems that amount his main interest are: online communities of practice and the way they evolve in time product design, simplicity in design and accessibility productivity and the way the IT solutions are impacting it

Updated on July 27, 2022

Comments

  • sorin
    sorin almost 2 years

    I do have an URL which opens a webpage which is very slow to load and I have no control over it.

    I do want to display a loading dialog when someone clicks this URL or to block page with an overlay div when this happens.

    Note: this is not the same question as the ajax related ones, this for normal URL clicks form the user, not all of them only specific ones.

    <A href="http://veryslowload.com" onClick="...">slow load...</a>
    

    I suppose that what I am looking for is what to put on the onClick.

  • bfavaretto
    bfavaretto over 11 years
    I'm surprised that just works. As you can see on my answer, I assumed the document would never be updated unless you forced a repaint.
  • Denys Séguret
    Denys Séguret over 11 years
    This just adds the div before the normal link behavior is triggered. The browser doesn't remove the current page from display until it has something to display for the new one.
  • bfavaretto
    bfavaretto over 11 years
    Yes, it doesn't remove the current page, but I thought the unload/load operation would block further updates, and it doesn't.
  • David Hellsing
    David Hellsing over 11 years
    Except that cross-domain ajax requests are generally not allowed because of browsers Same Origin Policy.
  • AmericanUmlaut
    AmericanUmlaut over 11 years
    @David Oh yeah. :( Does that behavior also block the loading of cross-domain iFrames? Because that would allow pseudo-AJAX using a temporary <iframe> to still work.
  • ThdK
    ThdK about 6 years
    Be aware that on some devices / browser combo this loadingDiv might still be visible when navigating back to this page using the browser back button? Am I correct?
  • Isuru Dilshan
    Isuru Dilshan about 5 years
    404 That page doesn't exist.
  • Mohsin Khan
    Mohsin Khan over 2 years
    this solved my problem, because i am using ajaxStart fucntion, and the page will get load on this gif loading.