Untitled UI logotext
Solutions
WebsitesEcommerceMobile AppsWeb AppsProduction Support & Maintenance
Our work
Company
About usBlogPodcastContact us
Book a free consultation

How to Speed up jQuery: Selector Tip

Olivia Rhye

I ran into a slow jQuery selector in older browsers on a large document and learned a cool tip: jQuery selectors should get more specific from left to right. Selectors are parsed in reverse order, so making sure that your most specific selector is on the right will increase performance.

The example below shows how not to write a jQuery selector using this technique:

$('p#intro b').each(function() {
//Do something
});

In the above example, jQuery finds all elements of type 'b' and then looks to see if the have a parent of p#intro.

Instead, it is recommended that you use the find function to speed up your jQuery. This took my 30,000 element document parsing time from 15 seconds to about 2:

$('p#intro').find('b').each(function() {
//Do something faster
});

This example does the opposite, finding a elements matching p#intro and looking in their children using the find() function to find all elements of type 'b'.

Ready to start a project?

Book a free consultation
Untitled UI logotext
Our work
About us
Blog
Careers
Submit a ticket
Agency Partnerships
Contact
© 2024 fjorge. All rights reserved.
Privacy