views:

27

answers:

1

I was in search of a way to show a status indicator using jQuery and I found a solution in the jQuery Cookbook, it showed this solution

(function($) {
    $(document).ready(function() {
       $('#ajaxStatus')
         .ajaxStart(function() {
            $(this).show();
        })
         .ajaxStop(function() {
            $(this).hide();
        });

        .....
  })(jQuery);

then it cautioned,

If you experience performance issues in your application, it may be because of the cost of event propagation if there is a significantly large number of elements. In this case, setting global to false may give you a performance improvement.

So first should I use the solution showed above and will it be a performance issue as my site and js code gets larger and larger?

Should I avoid jQuery global events, just turn it off like the paragraph says?

Lastly, how do you guys show a simple indicator while an ajax request is being performed?

+3  A: 

Honestly, I think this caution is valid, but at the same time, outdated. Look at the jQuery source here: http://github.com/jquery/jquery/blob/master/src/event.js#L290

It shows how a global event is now handled:

if ( jQuery.event.global[ type ] ) {
  jQuery.each( jQuery.cache, function() {
    if ( this.events && this.events[type] ) {
      jQuery.event.trigger( event, data, this.handle.elem );
    }
  });
}

It used to be:

jQuery("*").add([window, document]).trigger(type, data);

So it's not triggering on every element like it used to, which made the large number of elements warning a very real concern, it instead loops over elements that have registered or the event, and only if any have registered, so it's much better on performance now.


For your questions:

So first should I use the solution showed above and will it be a performance issue as my site and js code gets larger and larger?

Yes, the solution above is just fine, I've yet to see a page large enough for this to be an issue, after the global events optimization I outlined above.

Should I avoid jQuery global events, just turn it off like the paragraph says?

Nope, you can pretty much ignore that paragraph is using any jQuery after this change was made.

Lastly, how do you guys show a simple indicator while an ajax request is being performed?

Exactly as you have in your question :)

Nick Craver
@Nick: Thank you so much Nick! Indeed, the book I referenced is written last year. Great to know things improved since, I'll use the solution then. Thanks.
ray247