16

I currently have this code and it's pretty simple

$('#window').load('http://mysite.com/mypage.php');

But it shows the content only after fully loaded and during that duration the #windows element remains empty. I want to show a loading image until the page loads. How should i do it? The jquery site explains nothing about it. (afaik)

5 Answers 5

20

Create a loading div first.

 <div id='loadingDiv'>
    Please wait...  <img src='path to your super fancy spinner' />
 </div> 

Hide this DIV initially and attach the code to show this div when ajaxCall starts and hide this when ajax call completes.

$('#loadingDiv').hide().ajaxStart( function() {
$(this).show();  // show Loading Div
} ).ajaxStop ( function(){
$(this).hide(); // hide loading div
});

Edit
There was some issue in SO formatting tags a while back. Added those again.

Sign up to request clarification or add additional context in comments.

3 Comments

OMG, what is wrong with SO formatting.. All formatting gone and LoadingDiv code is not displayed at all.
I added this in an another <script></script>, the loading gif showing ok but it never hides after the ajax response.
Probably worth noting that: As of jQuery 1.8, the .ajaxStart() method should only be attached to document. Source: api.jquery.com/ajaxStart
7

For this purpose you have to use a gif image. First of all change the html of #window to gif image until the content is loaded

Working Code

$('#window').html("<img src="image_url" />").load('http://mysite.com/mypage.php');

3 Comments

simple adding the image url resulted in the url being printed on the screen but this code worked well $('#window').html("<img src=\"loader.gif\" />").load('http://mysite.com/mypage.php');
One problem you might run into with this approach is that if the load fails for any reason, your image will just sit there and never go away. You need to add a complete handler to hide remove the image once it is finished.
yeah just use position property
4

1) Go to cssload.net and configure a spinner with shape, colors, speed and size. Download the code.

2) Put the style code into a css file

3) Put the div code into your html file, such as:

<div id="loadingDiv">
        Please wait...
        <div id="spinnerDiv">
            <div id="blockG_1" class="facebook_blockG">
            </div>
            <div id="blockG_2" class="facebook_blockG">
            </div>
            <div id="blockG_3" class="facebook_blockG">
            </div>
        </div>
    </div>

where the #spinnerDiv is the actual div from cssload.

4) In a js file, add the following jquery lines:

//*******************************
    // Loading div animation
    $(document).ajaxStart(function(){
          $("#loadingDiv").css("display","block");
        });
        $(document).ajaxComplete(function(){
          $("#loadingDiv").css("display","none");
        });

the ajaxStart is called whenever an ajax call starts; the ajaxComplete is called when the same call is completed.

5) If you do not want to see the spinner when the page is first loaded, make sure to add the following in your css file:

#loadingDiv{
display:none;
}

1 Comment

When posting please format your code so that it is more readable.
3

For async requests that I know have the potential to take more than a few milliseconds, I use Spin.js It does not have any external dependencies, and is cross-browser compatible

var opts = {
  lines: 13, // The number of lines to draw
  length: 10, // The length of each line
  width: 4, // The line thickness
  radius: 11, // The radius of the inner circle
  rotate: 0, // The rotation offset
  color: '#000', // #rgb or #rrggbb
  speed: 0.6, // Rounds per second
  trail: 32, // 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
};

var target, spinner;

$(function(){
    target = $('#window').get(0);
    spinner = new Spinner(opts);
    spinner.spin(target);
    setTimeout(function(){
        spinner.stop();
        $(target).html("Loading finished.");
    }, 3500);
});

see fiddle http://jsfiddle.net/y75Tp/73/ (update thanks to verbumSapienti)

1 Comment

your fiddle was missing Spin.js itself. please see my update
0

The jQuery load() method has a callback where you can get the xhr status. Using the spin.js loader (or any other load indicator), you can show, then hide when the .load() is complete. Note: this example will give a 404 since the file loaded does not exist, but the spinner load indicator works just the same.

 // create gloabal page spinner for loading stuff
 var opts = {
   lines: 13, // The number of lines to draw,
   length: 12, // The length of each line
   width: 4, // The line thickness
   radius: 15, // The radius of the inner circle
   scale: .5, // Scales overall size of the spinner
   corners: 1, // Corner roundness (0..1)
   color: '#000', // #rgb or #rrggbb or array of colors
   opacity: 0.25, // Opacity of the lines
   rotate: 0, // The rotation offset
   direction: 1, // 1: clockwise, -1: counterclockwise
   speed: 1, // Rounds per second
   trail: 60, // Afterglow percentage
   fps: 20, // Frames per second when using setTimeout() as a fallback for CSS
   zIndex: 2e9, // The z-index (defaults to 2000000000)
   className: 'spinner', // The CSS class to assign to the spinner
   top: '50%', // Top position relative to parent
   left: '50%', // Left position relative to parent
   shadow: false, // Whether to render a shadow
   hwaccel: false, // Whether to use hardware acceleration
   position: 'absolute', // Element positioning
 }
 var spinner = new Spinner(opts).spin();
 var target = $("#loader").append(spinner.el);

 $("#result").load("ajax/test.html", function(response, status, xhr) {
   if (status == "error") {
     var msg = "Sorry but there was an error: ";
     $("#result").html(msg + xhr.status + " " + xhr.statusText);
   }
   // remove loader
   $("#loader").empty();
 });
<script src="http://fgnass.github.io/spin.js/spin.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="loader">
</div>
<div id="result">
</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.