Is referencing a selector faster in jquery than actually calling the selector? if so, how much does it make a difference?

后端 未结 3 696
花落未央
花落未央 2021-01-13 02:55
$(preview-button).click(...)
$(preview-button).slide(...)
$(preview-button).whatever(...)

Is it a better practice to do this:

var p         


        
3条回答
  •  再見小時候
    2021-01-13 03:51

    It is much faster to use a named variable rather than passing jQuery a selector once for each action. However, as it was already mentioned, chaining is an optimal solution in most cases. You can see it for yourself. Here is a test I just did:

    
    
    

    UPDATE:

    Apparently Firefox does some kind of caching and the three cases perform very similarly. On the other side Chrome and Safari have a rather poor performance in Case 1, compared against cases 2 and 3 (especially as number or nodes increases).

提交回复
热议问题