Does jQuery do any kind of caching of “selectors”?

后端 未结 14 2004
挽巷
挽巷 2020-11-27 18:14

For example, will the first piece of code perform a full search twice, or is it smart enough to cache results if no DOM changes have occurred?

if ($(\"#navba         


        
14条回答
  •  有刺的猬
    2020-11-27 18:40

    Similar to your $$ approach, I created a function (of the same name) that uses a memorization pattern to keep global cleaner and also accounts for a second context parameter... like $$(".class", "#context"). This is needed if you use the chained function find() that happens after $$ is returned; thus it will not be cached alone unless you cache the context object first. I also added boolean parameter to the end (2nd or 3rd parameter depending on if you use context) to force it to go back to the DOM.

    Code:

    function $$(a, b, c){
        var key;
        if(c){
            key = a + "," + b;
            if(!this.hasOwnProperty(key) || c){
                this[key] = $(a, b);
            }        
        }
        else if(b){
            if(typeof b == "boolean"){  
                key = a;  
                if(!this.hasOwnProperty(key) || b){
                    this[key] = $(a);
                }
            }
            else{
                key = a + "," + b;
                this[key] = $(a, b);   
            }            
        }
        else{
            key = a;
            if(!this.hasOwnProperty(key)){
                this[key] = $(a);
            } 
        }
        return this[key]; 
    }
    

    Usage:

    a
    b

提交回复
热议问题