jQuery – Slow Selectors

Recently I was experiencing slow jQuery functions. Slow jQuery was especially slow as I added more elements to the page and especially in Internet Explorer and FireFox. I was not surprised by the browsers being slower than others, but the fact that the jQuery was slower than it should was a surprise.

It turns out it was the selector that I had been using; $(“#ElementID:visible”) was slow very slow. In a function that did nothing much, it ended up taking 10 seconds to run.  I tried the selector $(“#ElementID”) and it ended up running is less than a second.  A developer that I had been working with thought maybe for some reason that it was the :visible filter that was applying, but I needed it.   I looked for another way to get the same result and found the .filter method.  It turns out that $(“ElementID”).filter(“:visible”) made my function run in less than a second.

In short:
Do Not Use:  $(“#ElementID:visible”) – Slow
Do Use: $(“ElementID”).filter(“:visible”) – Fast

Published by

ldnDeveloper

Andrew Pallant (@LdnDeveloper) has been a web, database and desktop developer for over 16 years. Andrew has worked on projects that ranged from factory automation to writing business applications. Most recently he has been heavily involved in various forms for ecommerce projects. Over the years Andrew has worn many hats: Project Manager, IT Manager, Lead Developer, Supervisor of Developers and many more - See more at: http://www.unlatched.com/#sthash.8DiTkpKy.dpuf