Normally I love to keep my HTML code clean, semantic and free from either Javascript or CSS. I include my .JS and .CSS files at the top, and layer functionality on top of the DOM elements.
The positives of this are:
- Architectural separation of concerns
- Graceful degradation where Javascript or CSS isn’t supported
- Search-engine friendliness
There is one major negative:
- Performance problems in IE 6
Because all the events are attached to the elements through Javascript code, which accesses the DOM, performance in IE suffers.
This is especially so when using jQuery (which happens to be my favorite Javascript framework).
So it seems like I have two choices: either keep the code nice and neat, and have IE 6 users (around 20% of the user-base) complain, or “de-normalize” the code to improve IE 6 performance.
Is there a “middle way” in this situation? Or am I doomed?
Note: I’m not saying that my performance problems are caused by having Javascript in a separate file.
I can achieve wonderful performance in IE while keeping it in a separate file.
The problem is, I still have to put the actual event handlers into ‘onclick’ attributes in the HTML. For example:
<span onclick="doSomething()">More...</span>
It would be much nicer if I could just write:
<span id="more-button">More...</span>
And then assign it separately, in Javascript, with the following:
$("#more-button").click(doSomething);
Unfortunately, it seems this is bad for IE6 performance.
In a talk available at YUI Theater, Joseph Smarr talks about performance and states the opinion that it is ok to have
onmousedownhandlers and the like in your code for performance reasons instead of finding the DOM element and then attaching the event handler. However, I do not know any measures by which that speeds up things. Other techniques for unobtrusive performance boosts are (EIDT: note that they are browser independent, hence not restricted to IE):onmousedowninstead ofonclick. Smarr says there is a 100ms or so period between the firing of the two events.window.setTimeout(visualFeedback, 0). That lets the browser draw some graphical change instantly, letting the user know that something is happening.There is also a demo that shows the benefit of the first two points. The button at the top uses
onclickand normal execution, the one below usesonmousedownandsetTimeout(func, 0).