I have a JavaScript that loops through a xml to display content. It take about 3-5 seconds to complete. In the mean time, I would like to incorporate a loading gif, however, the gif is load animating until after the JavaScript is complete. By that time, I want to to disappear. (For testing purposes, I did not have it disappear to ensure the gif was in fact working. Below I have what works to display and hide the gif content, so that I don’t need help with.
I think my idea is related to How to show loading gif image while content called via javascript is loading? however different that it does not use buttons to call JavaScript, it’s called when the page is loading.
In .html
<div id="loading"><img src="loading.gif"/>Starting Content</div>
In .js
function Loaded(quantity) {
$(document).ready(function() {
$("#loading").html("New Content");
});
}
As I said, the idea works to show/hide the gif, just the gif fails to animate which defeats the purpose of having it. 🙂
Long-running JavaScript jobs block the browser’s UI, including image animations. To see this in action:
Go to http://www.ajaxload.info/ and click “Generate it!” to make a GIF spinner.
Run
i=0; while(i < 100000000) i++;in your browser console. The image will freeze while the loop completes.In order to prevent this from happening, you’ll need to make your loop have some kind of asynchronous component as described in Javascript – how to avoid blocking the browser while doing heavy work? (this question is very nearly a duplicate of that one, in fact):
This queues up the steps of the loop, but it allows the JavaScript thread to “rest” between iterations of the loop, which in turns allows the UI thread to animate the GIF.