I am using Backbone and decided that I wanted a way to differentiate between HTML elements that were bound and those that were not.
So I would write (in HAML):
.container
.title(name='title')
.separator
As you can see it’s clear that the dynamic element is title.
The reason for this was so I could mess around with the style and rename classes without worrying about breaking the app. It also means in the template I can tell what the dynamic elements are without needing to go back and forth with the Backbone View.
This means that I use $('[name=title]', this.el) to reference this element from code. I am wondering if this is slow and be a noticeable issue if used everywhere. I have read that id is fastest. I am using lists of items so id is unrealistic. How does class compare to name lookups?
Also, if you have suggestions about keeping track of dynamic elements in HTML templates I’d love to hear them.
FYI:
-
I got the idea because I was originally using the Backbone.ModelBinding plugin which used
data-bindattributes for dynamic elements, but I am moving away from it now. -
I’m using CoffeeScript, Backbone and haml_coffee templates.
-
I’ve also read the
$(this.el).find('[name=title]')is faster than providing context to the selector.
Follow-up question:
A convention for indicating whether an HTML element is referenced from JS code
Updated jsperf to test all suggestions:
Searching the name attribute of a DOM element might be a little bit slower than the class due to the need for Sizzle – the selector engine that jQuery uses – would need to parse the selector in order to determine exactly what needs to be found. Sizzle would need to determine from the string “[name=title]” that it first needs to be looking at the “name” attribute of all elements being searched and that the value of that attribute is “title” exactly. While I have read that Sizzle is very fast what it does I can only guess that it is going to be slower than a native JavaScript call to a DOM element attribute – class (element.className) – value.
To confirm my suspicions I made a perf: http://jsperf.com/class-or-name-attr-lookup. The results aren’t what I would have suspected on the .find and .children calls but what I stated above seems to be supported in the first two examples at least. However, I have seen performance boosts in production code when using the most specific selector – e.g. .children instead of .find – as it isn’t looping over unnecessary elements.
Also, I made a test a while ago to illuminate some of the differences between using a simple selector syntax and some more obscure and/or jQuery-ish syntax to compare performance that I thought was interesting: http://jsperf.com/id-id-vs-id-class/2.
I Hope some or any of this helps anyone.