我可以在jQuery中缓存$(window)和$(document)吗? [英] Can I cache $(window) and $(document) in jQuery?
问题描述
我最近阅读了一些有关jQuery性能的文章,并且提出了一些奇怪的问题.
I recently read some articles regarding jQuery performance, and I came up with some weird questions.
-
我可以/应该缓存
$(window)
吗?
如果我这样做了,会影响resize
,scroll
,width
,scrollTop
...等吗?
If I did, would it affect resize
, scroll
, width
, scrollTop
...etc?
我可以/应该缓存$(document)
吗?
由于我们使用了许多鼠标操作,我应该执行var doc = $(document);
吗?
As we use a lot of mouse actions, should I do var doc = $(document);
?
我可以总是在大量代码中缓存$(this)
吗?
Can I always cache $(this)
in a big block of code?
对于var self = $(this);
,在什么条件下self
可能与$(this)
不同?
As for var self = $(this);
, in what condition that self
might be different from $(this)
?
推荐答案
所有三个问题:是的,可以!
日用品:否
更好的表现:也许
您可以尝试进行基准测试.但是,缓存的原因不是在整个DOM中搜索您的选择器.查找文档和窗口不是问题,因为它们是2个根变量.缓存$(this)取决于情况.请参阅我的第二个提示.
You could try and do a benchmark. But the reason for caching is not to search entire DOM for your selector. Looking up document and window isn't a problem because they are 2 root variables. Caching $(this) depends on situation. See my 2nd tip.
始终缓存在其上运行查询的父对象:
var header = $('#header');
var menu = header.find('.menu');
// or
var menu = $('.menu', header);
链接jQuery方法比缓存选择器更好:
$('li.menu-item').click(function () {alert('test click');})
.css('display', 'block')
.css('color', 'red')
fadeTo(2, 0.7);
缓存经常查询的元素:
var header = $('#header');
var divs = header.find('div');
var forms = header.find('form');
免费的额外性能提示:
选择器的速度最慢:
Id > Tag > classes
这篇关于我可以在jQuery中缓存$(window)和$(document)吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!