PseudoSavant

The Musings of Paul Ellis

  • About me
  • JS 101: Cache your selectors

    javascript-icon.pngOne of the slowest things you can do with JavaScript is work with the DOM. And one of the slowest DOM operations is performing a query to find DOM elements. Caching those queries can have significant performance impacts. Here’s how you do it.

    Here is an example of the type of code you shouldn’t write, but that I have seen many times. It needs to make multiple changes to some element(s) and performs the query selector each time it is needed.

    You can ‘cache’ the response of queries you know you’ll use again in a variable however. Then each time you need to operate on those elements you just use the variable your assign them to. If there are queries you would use in multiple places in your app it can be a good idea to cache many queries at the start of your app so that you can reference them later.

    Another good common practice is to prefix your cached variables with a `$` (like $ with jQuery) to indicate that it is a query response. I follow this pattern even when I don’t use jQuery as seen in the example above.

    Another reason to use cached queries is that you can perform queries on all of the child elements of that element. Suppose you have a form and you will be working with many of the fields in the form to validate and submit the form. In this scenario I will typically query for the form first and then find the child elements of the form. In the example below it means instead of looking at every `input` on the page and checking whether it is a descendent of `.myForm` it will just look at the input fields that are child elements of `.myForm`.

    The best way to manage caching of your queries though is to make the computer do it for you automatically. The function(s) below wrap around the native DOM `querySelectorAll` or jQuery and will automatically cache every object you lookup using them. This is actually better than caching your selectors in advance because the client only suffers the performance impact when that query actually gets done.

    Filed In: Uncategorized
    January 30, 2014
  • Subscribe via Email

    Enter your email address to receive new posts to this blog in your inbox. I'll never mail anything else. Seriously.

  • Links

    • GitHub
    • Homemarks
  • Recent Posts

    • Meta “When is it stealing?” Inception.
    • Craftsman
© 2026 J. Paul Ellis