Andreas Grabner About the Author

Andreas Grabner has been helping companies improve their application performance for 15+ years. He is a regular contributor within Web Performance and DevOps communities and a prolific speaker at user groups and conferences around the world. Reach him at @grabnerandi

101 on Prototype CSS Selectors

Performance implications of certain CSS Selectors are not specific to a certain JavaScript Library like Prototype. I recently blogged about the internals of CSS Selectors in jQuery. The same holds true for every JavaScript library that offers CSS Selectors. Certain lookups can be done by using the native browser functions like getElementById or getElementsByTagName. Lookups by class name are not natively supported in IE and are therefore implemented in JavaScript by iterating through all elements in the DOM – which is obviously much slower than a native implementation.

Expensive Prototype CSS Selector

I recently analyzed some pages of an online retail store that uses Prototype. I used the dynaTrace AJAX Edition to identify the root cause of several slow pages on that web site. I identified two specific examples of CSS Selectors that caused massive overhead on that particular page:

$$(“[id^=contentElement]“) -> up to 6 seconds on a single page to find all elements that have an id starting with contentElement

$$(“div[class=contentDiv]“) -> up to 2.3 seconds on a single page to find all div tags with the class contentDiv

Selector Expressions

The flexibility that you get with CSS selectors is great. As you can see from the examples above you can use certain operators to do not only lookup elements by their full id, tag or class name. The following operators are supported (taken from prototype 1.6.1)

  • [id=contentElement] -> finds the element with the id that matches contentElement
  • [id!=contentElement] -> finds all elements that do not match contentElement
  • [id^=contentElement] -> finds all id’s that start with contentElement
  • [id$=contentElement] -> finds all id’s that end with contentElement
  • [id*=contentElement] -> finds all id’s that include contentElement

Additionally to these we have two selectors that allow you to query for elements with attribute values containing hyphen or space separated list values.

  • [sample~=value] -> finds all elements whose sample attribute is a list of space-separate values and one of them has the value “value”
  • [sample|=value]-> finds all elements whose sample attribute is a list of hyphen-separate values and one of them has the value “value”

When using expressions like the ones above (except id=contentElement) Prototype needs to iterate through all DOM elements and manually match the DOM’s attribute value with the expected value as there is no native implementation available for this feature by the browser. Depending on the size of your DOM this can cause a huge performance impact.

Sample 1 – Find elements which attributes that start with a certain text

The following screenshot shows the custom JavaScript method that uses the [id=^contentItemContainer] expression to get all elements that have an id attribute starting with contentItemContainer. The page had a total of 3184 DOM elements. The used expression causes Prototype to use getElementsByTagName(“*”) which returns ALL 3184 elements. Prototype then iterates through all elements. It reads the attribute in question (id) and verifies if it starts with the passed value (contentItemContainer). Additionally to that it reads all sort of other DOM attributes depending on the DOM Element Type (a, td, p, h1, h2, …) and registers the prototype extension methods (more on this in Sample 2 of this post).

In this example the CSS Expression caused 191454 interactions with the DOM.

Expensive CSS Selector causing 190k DOM Calls

Expensive CSS Selector causing 190k DOM Calls

There are multiple solutions to this problem. One is to find a better way to identify these elements. Looking at the HTML document showed me that all these contentItemContainer elements were in fact DIV tags. Changing the query to $$(“div[id=^contentItemContainer]“) would have caused Prototype to use getElementsByTagName(“div”) which would have only returned 178 elements instead of 3184.

In case these elements have different tags this first approach wouldn’t work. Limiting the number of DOM elements on the page would be another option to speed up iterating through all elements.

Sample 2 – Find elements by class name

This is the classic example which only holds true for Internet Explorer. As discussed in my previous post about jQuery Selectors - IE does not support a native method to get elements by class name. Using a query like “[className=contentDiv]” would therefore be handled in the same way described in Sample 1 – all DOM elements are iterated to find those elements that match the class name.

What was surprising to me was that the query $$(“div[className=contentDiv]“) still triggered many more DOM interactions than I expect. Using the “div” tag in the expression solves the problem that not all DOM elements are iterated but just the DIV tags using the native getElementsByTagName to get these elements. On those returned DIV elements Prototype defines it’s extension methods like previousSiblings, nextSiblings, match, up, down, … In my case I had 618 DIV tags. On each of these objects Prototype registered 57 extension methods. This “registration” in the end took most of the time of the item lookup.

Selector registering extension methods
Selector registering extension methods

The query div[className=contentDiv] caused a total of 42415 DOM interactions even though I only had 618 DIV tags on the page where about 200 matched the passed className. I am wondering if there is a way to configure Prototype to not register the additional extension methods in case they are not needed on a particular web page. Any thoughts on this?

Conclusion

As with any JavaScript framework that offers a variety of CSS Selectors you need to know what is actually going on when using them. They are flexible and easy to use. But keep in mind that certain browsers (especially IE) have limitations when it comes to selections by Class Name. Also – the larger the DOM Tree becomes the more overhead you have when using any other lookup method than by id or tagname – in all these cases the JavaScript framework needs to iterate the complete DOM. As always – I am happy for feedback.

Comments

  1. I realise that this is probably bad for ecommerce sites, but for the most part, I could care less if they are using IE6 and the site is a little slow. They are using a browser from 2001, it is almost 8 years old. They should be grateful that I put in the effort to make it work. If more sites were slow, they might be inclined to upgrade their browser.

  2. @SeanJA:You are correct-it is an old browser-but many people are still using it.But it is not just IE6. 7 & 8 also do not support getElementsByClassName which makes lookups by classname very slow on these browsers.

  3. Sometimes the usual tools from your DOM arsenal document.getElementById() encapsulated by $(), getElementsByTagName() and even Prototype’s very own getElementsByClassName() extensions — just aren’t enough to quickly find our elements or collections of elements. If you know the DOM tree structure, you can simply resort to CSS selectors to get the job done.

  4. @vitamin_c: you are right-you can do a lot with pure CSS – but – with all these dynamic web apps JavaScript is used to modify your DOM – and then you need a way to query those elements that need to be modified. Thats where performance really becomes an issue – I dont see a way to completely avoid lookups using $ or $$ by using strict CSS. Thoughts?

  5. This was a great article, it really helped me a lot. Thanks!

  6. Over the past 6 months or so Javascript has really gotten a lot of attention. I can’t name a web application released in the previous months that doesn’t use Javascript to provide an enhanced experience for users. I wanted a way to facilitate that interaction that doesn’t involve me repeating myself over and over wiring and rewiring event ovservers to a document.

  7. Awesome, thanks … had some issues with [id^=string] in IE6 with Prototype, managed to go from a selector taking 13 seconds to less than a second.

  8. @Dever: great success story :-)

  9. I wanted a way to facilitate that interaction that doesn’t involve me repeating myself over and over wiring and rewiring event ovservers to a document. This was a great article, it really helped me a lot.
    nexium vs prilosec

  10. I am very happy to discover your post as it will become on top in my collection of favorite blogs to visit. Brilliant article my friend, but could you teach me more detail about your post.
    IT jobs

  11. Nice article. It really helped me when I was setting up the transactional replication. bank career

  12. I wonder how you got so good. HaHa! This is really a fascinating blog, lots of stuff that I can get into. One thing I just want to say is that your design is so perfect! Freshersworld

  13. I realise that this is probably bad for ecommerce sites, but for the most part, I could care less if they are using IE6 and the site is a little slow. They are using a browser from 2001, it is almost 8 years old. They should be grateful that I put in the effort to make it work. If more sites were slow, they might be inclined to upgrade their browser.Classifieds

  14. I need to read more on this topic…I admiring time and effort you put in your blog, because it is obviously one great place where I can find lot of useful info. sarkari naukri

  15. This was a great article, it really helped me a lot.

Trackbacks

  1. [...] 101 on Prototype CSS Selectors Performance, Scalability and … [...]

  2. [...] 101 on Prototype CSS Selectors [...]

  3. [...] 101 on Prototype CSS Selectors Performance, Scalability and Architecture – Java and .NET Appli… – As with any JavaScript framework that offers a variety of CSS Selectors you need to know what is actually going on when using them. They are flexible and easy to use. But keep in mind that certain browsers (especially IE) have limitations when it comes to selections by Class Name. Also – the larger the DOM Tree becomes the more overhead you have when using any other lookup method than by id or tagname – in all these cases the JavaScript framework needs to iterate the complete DOM. [...]

  4. [...] can very often be seen when expensive CSS Selector Lookups (check out the blogs about jQuery and Prototype CSS Selector Performance) are used or when using dynamic elements like JavaScript Menus (check out the blog about dynamice [...]

  5. [...] performance. Check out the following blog entries about the performance impact of jQuery and Prototype. It shows how important it is for developers to understand the internals of frameworks in order to [...]

  6. [...] about different best practices on things like correct usage of CSS Selectors with jQuery and Prototype and showed the performance impact of bad JavaScript code and incorrect jQuery usage by analyzing [...]

  7. [...] // Many times have we been posting the recommendation to speed up your DOM Element lookups by using unique IDs or at least a tag name. So, instead of using $(“.wishlist”) you should use $(“div.wishlist”) which will speed up lookups in older browsers. If you want to lookup a single element then give it a unique ID and change your call to $(“#mywishlist”). This will speed up lookup in older browsers from 100-200ms to about 5-10ms (times vary depending on number of DOM elements on your page). More on this in our blogs 101 on jQuery Selector Performance or 101 on Prototype CSS Selectors. [...]

  8. [...] can very often be seen when expensive CSS Selector Lookups (check out the blogs about jQuery and Prototype CSS Selector Performance) are used or when using dynamic elements like JavaScript Menus (check out the blog about dynamice [...]

Comments

*


one + = 9