我知道 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 非常复杂),但是会有有所不同 http://jsperf.com/jquery-cached-selector:
Update
jQuery 会保留对 elems 的引用并在内部缓存 $(elems) 吗?
它不必每次都应用相同的 $() 包装器?
不,不会的。如上所述,对匹配的元素集的引用将不会保留在其适用的语句之外。您可以通过保留对整个过程中使用的 jQuery 对象的引用来提高代码的性能,而不是每次都再次选择它们,甚至每次都将一组存储的本机 DOM 节点包装在 jQuery 对象中。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)