jQuery Optimization/Best Practices

前端 未结 6 1658
傲寒
傲寒 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:11

    Up to your questions:

    1. Caching the jQuery object should yield best performance. It will avoid DOM lookups which is what can get slow when performed many times. You can benefit from jQuery chaining - sometimes there is no need for a local variable.
    2. The same goes with $(this) when this is a DOM element. Despite the fact that this is the fastest way to obtain a jQuery object it is still slower than caching. If the vanilla DOM element would suffice - then don't call jQuery at all. The example with the id attribute is excellent - prefer this.id than $(this).attr('id) if you are not going to need $(this)
    3. More specific selectors will decrease the DOM lookup time indeed. However there is indeed a line to be drawn - make the selectors more specific only if you are 100% sure this would improve performance in a noticeable way.

提交回复
热议问题