Is storing jQuery elements in variables more efficient?

后端 未结 5 604
悲&欢浪女
悲&欢浪女 2021-01-05 00:20

Which is more efficient please?

var myElement = $(\"#the-name-of-my-element\")

myElement.doSomethingOnce;
myElement.doSomethingTwice;
...
myElement.doSometh         


        
相关标签:
5条回答
  • 2021-01-05 00:46

    It is always good practice to cache your nodes. The amount of work the JS engine has to do to locate the nodes is more expensive than the memory that you will use storing the node (of course unless you are storing a massive DOM tree or something).

    So the winner is:

    var myElement = $("#the-name-of-my-element")
    
    myElement.doSomethingOnce;
    myElement.doSomethingTwice;
    ...
    myElement.doSomethingTenTimes;
    
    0 讨论(0)
  • 2021-01-05 00:47

    Using $("#the-name-of-my-element") everytime dom element search is performed.

    Using var myElement = $("#the-name-of-my-element") dom element search is performed only once and then stored to variable. So next time it will be accessed faster and without additional functions called.

    So, in conclusion - assigning element to variable if you have to use it several times is more efficient than searching it every time.

    0 讨论(0)
  • 2021-01-05 01:00

    with $("#the-name-of-my-element") jQuery is traversing the entire dom tree to find all elements which apply to the selector rule.

    Thus, putting the result in to a variable and using that instead of using the same selector a couple of times will be more efficient.

    Caveats: if one of the called method (doSomeThing..()) adds a new element with the same selector, this element won't be treated. As long as it's an ID, fine, but might be a problem when using classes (".someclass")

    0 讨论(0)
  • 2021-01-05 01:03

    jQuery does not cache selectors - as detailed in this question:

    Does jQuery do any kind of caching of "selectors"?

    As a result, each time you perform $("#the-name-of-my-element") jQuery is performing some work to match the selector.

    For anything other than trivial code, I'd always cache selectors.

    See also ...

    At what level should I cache results of jQuery DOM queries?

    0 讨论(0)
  • 2021-01-05 01:04

    If you are doing multiple tasks with same element than it's better to cache it to variable so JS will not re-select element on every call.

    Also it's easier to maintain your code - e.g. if you want to change selector, than you have to change it in one place instead of going through code and searching for it.

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