我知道 jQuery 不会缓存元素集合,f.ex 调用:
$('.myclass').html('hello');
$('.myclass').html('bye');
将使 jQuery 爬取 DOM 两次。
但是缓存的 DOM 节点呢?
var elems = document.querySelectorAll('.myclass');
$(elems).html('hello');
$(elems).html('bye');
jQuery 会在内部缓存它们吗,或者它们会像第一个示例一样慢吗?
澄清:jQuery 是否会保留对 elems
的引用并在内部缓存 $(elems)
,这样它就不必应用每次都使用相同的 $()
包装器?
类似于:
cache = {}
constructor = function(collection)
if collection in cache
return cache[collection]
else construct(collection)
最佳答案
假设我已经正确理解了你的问题,那么不,jQuery 不会在使用它们的语句之外保留对选定节点的引用:
$('.myclass').html('hello'); //Select all .myclass elements, then change their HTML
$('.myclass').html('bye'); //Select all .myclass elements, then change their HTML again
如果您分别维护对那些选定节点的引用,它会更快:
var elems = document.querySelectorAll('.myclass'); //Select all .myclass elements
$(elems).html('hello'); //Change their HTML (no need to select them)
$(elems).html('bye'); //Change their HTML (no need to select them)
差异不会很大(除非您的 DOM 非常复杂)但会有 be a difference :
更新
will jQuery keep a reference to elems and cache $(elems) internally so it won’t have to apply the same $() wrapper every time?
不,不会。如上所述,对匹配元素集的引用将不会在其适用的声明之外保留。您可以通过保留对自始至终使用的 jQuery 对象的引用来提高代码的性能,而不是每次都重新选择它们,甚至每次都将一组存储的 native DOM 节点包装在 jQuery 对象中。
关于javascript - jQuery 是否在内部缓存元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12276787/