Why cache jQuery objects?

前端 未结 2 820
面向向阳花
面向向阳花 2020-11-27 19:40

So why are we supposed to cache jQuery objects?

In the following scenario:

var foo = $(\'#bar\');
foo.attr(\'style\',\'cool\');
foo.attr(\'width\',\'         


        
相关标签:
2条回答
  • 2020-11-27 20:15

    Because the jQuery function has a lot of code in it, which involves unnecessary overhead if you execute it more than once with the same inputs expecting the same outputs. By caching the result, you store a reference to the exact element or set of elements you're looking for so you don't have to search the entire DOM again (even if it's a fairly fast search). In many cases (simple pages with small amounts of code) you won't notice a difference, but in the cases where you do it can become a big difference.

    You can see this in action by testing your example in jsPerf.

    You can also think of it as an example of the Introduce Explaining Variable refactoring pattern for readability purposes, particularly with more complex examples than the one in the question.

    0 讨论(0)
  • 2020-11-27 20:28

    The jQuery selector $('#foo') searches the entire DOM for the matching element(s) and then returns the result(s).

    Caching these results means that jQuery doesn't have to search the DOM every time the selector is used.

    EDIT: document.getElementById() is what jQuery uses to search the DOM, but there's never enough jQuery.

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