I have an autocomplete form where the user can type in a term and it hides all <li>
elements that do not contain that term.
I originally looped through all <li>
with jQuery's each
and applied .hide()
to the ones that did not contain the term. This was WAY too slow.
I found that a faster way is to loop through all <li>
and apply class .hidden
to all that need to be hidden, and then at the end of the loop do $('.hidden').hide()
. This feels kind of hackish though.
A potentially faster way might be to rewrite the CSS rule for the .hidden
class using document.styleSheets
. Can anyone think of an even better way?
EDIT: Let me clarify something that I'm not sure too many people know about. If you alter the DOM in each iteration of a loop, and that alteration causes the page to be redrawn, that is going to be MUCH slower than "preparing" all your alterations and applying them all at once when the loop is finished.
$
thousands of times. – Becalmedhide()
all the.hidden
elements? Shouldn't that be already defined in your stylesheet? – HydrosomemaxSearchResults
amount of lis at a time... – Evvie$('.hidden').hide()
is just calling.hide()
a whole bunch of times in a loop too - there's no magic in jQuery. We have to see the ACTUAL code to diagnose a performance issue. – Ginnhide()
calls in a loop, it would have to assume the user doesn't care about progressively hiding things (there may be asleep()
function after eachhide()
for instance and the results of the previous hide call must show on the screen). I amended thehide()
in jQuery's source with my own counting function, and you are actually wrong -- it calls and reflows the page once on each loop iteration. – Metzlersleep()
in javascript . The browser knows when the JS execution thread is running vs. done and it's single thread so it's simple and the browser is under no obligation to update the screen until the JS thread is finished running. No browser I know of causes layout between successivehide()
calls unless you refer to a specific CSS property betweenhide()
calls that requires layout to be refreshed in order to obtain that property accurately. I can do 1000hide()
calls extremely fast with no refresh between them when written properly. – Ginnsleep()
in Javascript. That was just an example -- a placeholder for anything that consumes time. I would have thought the context of the sentence implied that. You say "No browser I know of causes layout between successivehide()
calls unless you refer to a specific CSS property betweenhide()
calls that requires layout to be refreshed in order to obtain that property accurately". Well check out this: jsfiddle.net/GekPY No reference to any CSS properties and it redraws the page every for loop. – Metzler.hide()
operations: jsfiddle.net/jfriend00/fVPz7. – Ginn