performance - Can I cache $(window) and $(document) in jQuery? -
i read articles regarding jquery performance, , came weird questions.
can/should cache $(window)
?
if did, impact resize
, scroll
, width
, scrolltop
...etc?
can/should cache $(document)
?
as utilize lot of mouse actions, should var doc = $(document);
?
can always cache $(this)
in big block of code?
as var self = $(this);
, in status self
might different $(this)
?
all 3 questions: yes can!
neccessery : no
better performance: maybe
you seek , benchmark. reason caching not search entire dom selector. looking document , window isn't problem because 2 root variables. caching $(this) depends on situation. see 2nd tip.
always cache parent object run queries on:
var header = $('#header'); var menu = header.find('.menu'); // or var menu = $('.menu', header);
it’s improve chain jquery methods cache selectors:
$('li.menu-item').click(function () {alert('test click');}) .css('display', 'block') .css('color', 'red') fadeto(2, 0.7);
cache elements query often:
var header = $('#header'); var divs = header.find('div'); var forms = header.find('form');
a free performance tip:
selectors fastes slowest:
id > tag > classes
jquery performance caching
No comments:
Post a Comment