jQuery Optimization/Best Practices

前端 未结 6 1625
傲寒
傲寒 2020-12-07 13:06

Ok saddle up cowboys, because this is going to be a long one. I have been spending the morning going through some of my old code and I\'m left wondering about best practices

6条回答
  •  北海茫月
    2020-12-07 13:31

    I'll try to answer these as concisely as possible:

    1. Cache it when it's used often, especially in a loop situation, running the same code to get the same result is never a good thing for performance, cache it.

    2. Use this when you only need a DOM element and $(this) when you need the jQuery methods (that wouldn't be available otherwise), your example of this.id vs $(this).attr("id") is perfect, some more common examples:

      • Use this.checked instead of $(this).is(':checked')
      • Use $.data(this, 'thing') instead of $(this).data('thing')
      • Any other case where creating a jQuery object isn't useful basically.
    3. Decending from an ID selector is preferred for performance...how specific do you need to be? That completely depends, in short: be as specific as you need to be.

提交回复
热议问题