Should I cache $(this) in jQuery if it is used more than once?

后端 未结 4 1600
故里飘歌
故里飘歌 2020-12-11 05:20

I know that you are supposed to cache the results of a selector if you use it more than once. An example would be:

var $selected = $(\'.some-selected-elemen         


        
相关标签:
4条回答
  • 2020-12-11 05:53

    The $() function finds the DOM node for the element and applies the prototyped methods to it for browsers that don't already add them when defined (IE browsers). So constantly calling it will perform this operation. It is better for performance and readability to cache the output of the $() function call to a variable.

    0 讨论(0)
  • 2020-12-11 05:54

    Yes, there's a performance increase, because it prevents jQuery from having to interpret your selector.

    Here's the interpretation of a selector, and what you'll be bypassing. https://github.com/jquery/jquery/blob/master/src/core.js#L78-188

    Essentially, this part

    if ( selector.nodeType ) {
        this.context = this[0] = selector;
        this.length = 1;
        return this;
    }
    
    0 讨论(0)
  • 2020-12-11 06:11

    Yes, there are performance benefits.

    Caching the result of $(this) avoids multiple calls to the $() function and the creation of several different jQuery objects that all refer to the same element.

    0 讨论(0)
  • 2020-12-11 06:13

    jsperf.com is a great resource - and one I've taken to frequenting of late - for evaluating JavaScript performance. For example, the following test evaluates the performance of cached jQuery elements to that of non-cached:

    http://jsperf.com/jquery-cache-vs-no-cache

    The results echo the answers in this thread.

    0 讨论(0)
提交回复
热议问题