Performance of jQuery selectors vs local variables

后端 未结 5 1412
清歌不尽
清歌不尽 2020-12-03 07:24

Is it recommended that, when I need to access the result of a jQuery selector more than once in the scope of a function, that I run the selector once and assign it to a loca

5条回答
  •  悲&欢浪女
    2020-12-03 08:12

    You're actually forgetting the truly cached approach.

    The thing with jQuery is that the initial lookup: $('.selector') is expensive. But after that, chaining your actions onto it, or assigning it to a variable and executing your actions on the variable don't matter that much. The main performance gain you can get is caching the element even further, and not assigning the jQuery selector each iteration of your function call.

    var element = $('.myElement');
    var execute = function(){
        element.css('color','green');
        element.attr('title','My Element');
        element.click(function(){
            console.log('clicked');
        });
    }
    

    This approach is almost twice as fast as the fastest version from the other approaches suggested.

    See http://jsperf.com/caching-jquery-selectors/17

    Note: If your DOM changes during it's lifetime, you can update the element variable with the a fresh selection of elements.

提交回复
热议问题