Should I cache jQuery selectors in the global namespace?

Details:

Commonly used jQuery caches should be cached.

var $thing = $("#thing"); // ...lots of invocations of $thing... 

It can be convenient (and sometimes possibly more dynamic ) to select an external div, and then use .find() to get the inner element, re going to grab a few things from this div.

 var $outerDiv = $("div#outer"); var $thing1 = $outerDiv.find(".thing1"); var $thing2 = $outerDiv.find(".thing2"); // ...etc.... 

But what if I have many external divs and never use them after initially looking for the necessary children?

 var $outerDiv1 = $("div#outer1"); var $foo1 = $outerDiv1.find(".foo1"); var $foo2 = $outerDiv1.find(".foo2"); // ...etc.... var $outerDiv2 = $("div#outer2"); var $bar1 = $outerDiv2.find(".bar1"); var $bar2 = $outerDiv2.find(".bar2"); // ...etc.... 

Now I have $outerDiv1 , $outerDiv2 , etc., seated in the global namespace occupying memory.

My questions:

  • Should I cache jQuery selectors in the global namespace in general? Why not)?
  • If I put cached selectors in some namespace other than global, will the cleared $outerDiv* variables $outerDiv* cleared in the garbage collection?
  • Are the performance / benefit costs negligible anyway for a typical webpage?

Note:

My question suggests the truth of the accepted answer to the question "jQuery object: cache or not cache?" . This is not a duplicate, because it expands, considering the effect of memory, if we know that some of the global cached selectors will never be used again.

+5
source share

Source: https://habr.com/ru/post/1271348/


All Articles