Working Around the Problem

Most CSS experts are familiar with CSS expressions and how to avoid the pitfalls highlighted by the previous example. Two techniques for avoiding problems created by CSS expressions are creating one-time expressions and using event handlers instead of CSS expressions.

One-Time Expressions

If the CSS expression has to be evaluated only once, it can overwrite itself as part of its execution. The background style defined at the beginning of this chapter is a good candidate for this approach:

<style>
P {
    background-color: expression( altBgcolor(this) );
}
</style>

<script type="text/javascript">
function altBgcolor(elem) {
    elem.style.backgroundColor = (new Date()).getHours(  )%2 ? "#F08A00" : "#B8D4FF";
}
</script>

The CSS expression calls the altBgcolor( ) function, which sets the style's background-color property to an explicit value, and this replaces the CSS expression. This style is associated with the 10 paragraphs in the page. Even after resizing, scrolling, and moving the mouse around the page, the CSS expression is evaluated only 10 times, much better than the tens of thousands in the previous example.

Event Handlers

In most situations where I've seen CSS expressions used, it was possible to find an alternative that didn't require them. CSS expressions benefit from being automatically tied to events in the browser, but that's also their downfall. Instead of using CSS expressions, the ...

Get High Performance Web Sites now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.