The following example explains how can we display a loading image while requested content is being
loaded by one of the jQuery's AJAX functions. Here is what happens:
- Something triggers AJAX request (like "search" button click);
- We put the loading image or a text that ask for user patience to the place where we would later insert the loaded content (or anywhere else);
- After remote content is fully loaded, we remove/hide the loading image/text and insert the loaded content.
To make it more apparent, imagine we have HTML page with this markup:
<button id="btnLoad">Load Content</button>
<div id="content">
Please click "Load Content" button to load content.</div>
We want to load content when a user clicks on the "Load Content" button. So we need to bind a
click event to that button first and make AJAX request only after it is fired.
$("#btnLoad").click(function(){
// Make AJAX call
$("#content").load("http://example.com");
});
The above code loads contents from http://example.com into the
<div id="content">.
While the page is being loaded we want to display our animated GIF
image in the "content". So we could further improve our code like so:
$("#btnLoad").click(function(){
// Put an animated GIF image insight of content
$("#content").empty().html('<img src="loading.gif" />');
// Make AJAX call
$("#content").load("http://example.com");
});
The
.load() function would replace our loading image indicator with the loaded content.Important note:
You might be using jQuery’s other AJAX functions like
$.ajax(), $.get(), $.post(), in this case use their callback function to remove loading image/text and append your loaded data.
No comments:
Post a Comment