I have a page that displays a spinner animation while dynamic content is loaded asynchronously (HAML here):
#loading_spinner
#async_vote
:javascript
$(document).ready(function() {
$.ajax({
url: "/votes/voteables",
cache: false,
beforeSend: function(xhr){
$("#loading_spinner").show();
},
success: function(html){
$("#loading_spinner").hide();
$("#async_vote").html(html);
}
});
});
To simulate a slow request, I have put a sleep of a few seconds into the :voteables-method.
Now, the problem is that the browser does not show the background-image of the #loading_spinner-element.
What happens is that although the JavaScript-code should execute when the page is loaded, it actually executes the AJAX-call before it fetches the background-image for the spinner. So when the delay in the controller is 3 seconds, the image is loaded immediately afterwards (because the requests are not served in parallel), the success-callback is executed and the image is immediately hidden.
I am using Rails 3.2 and running the app with rails server.
Any recommendations how to fix this issue in development? And will it be an issue in production?
I think if you wrap the ajax request in load, instead of ready, it won’t execute until the images have downloaded, like this: