jQuery global events and performance?

扶醉桌前 提交于 2019-12-21 20:15:53

问题


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?


回答1:


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 :)



来源:https://stackoverflow.com/questions/3162748/jquery-global-events-and-performance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!