Bruce Williams is right on in Avoiding AJAX Faux Pas where he lists four inviolable conditions your AJAX code must meet. The first two conditions address the need to show (then hide) a visual progress indicator to let the user know that a network operation (XHR) is occurring. These are important rules. Unfortunately, the implementation he presents is fraught with difficulties.
Bruce’s solution is comprised of a Ruby function
showing_progress which he suggests you use in every single call to (
insert_html, replace_html, replace) to wrap any options you’d normally pass to those routines. The
showing_progress routine adds
:complete handlers that will show, then hide an element with id ‘progress’ on your page.
The solution is kind of elegant and it works as advertised but I ran into a few problems as I got deeper into my app:
- I forgot to call
showing_progressin new invocations of
insert_html, replace_html, replace— as a result I didn’t get progress indication in those cases
Ajax.Updaterthen the solution of course doesn’t help.
- The solution ruthlessly overwrites any :loading and :complete handlers you’ve defined in your options
Here’s the solution I’m using. I don’t recall where I first saw it but I’m pretty sure I didn’t invent it. I see Nicky Peeters was suggesting a similar thing over a year ago. Just put this code in application.js:
1 AjaxRespondersregister 2 3 if$'progress' && AjaxactiveRequestCount>0 4 EffectAppear'progress'duration:0.5queue:'end'; 5 6 7 8 if$'progress' && Ajax=0 9 EffectFade'progress'duration:0.5queue:'end'; 10 11 ;
And stick something like this in your layout:
1 2 3
And you’ll have one less worry in your life.