Conditional Comments: Obscure Decrement Behaviour
NOTE: This is not a bug, simply correct behaviour that results in an unexpected outcome.
There appears to be an obscure behaviour in some browsers when a conditional comment contains a decrement operator and the result is compared to an end value with a greater-than operator. The construct would look something like this:
Some browsers ignore the conditional comment completely, but a few appear to interpret the decrement and greater-than operators as the closing of the conditional comment.
I've identified this behaviour in Netscape (6.2, 7.1), iCab (3.0.2beta, 3.0.3), Firefox (1.0, 1.5, 2.0), and Camino (1.0.1). Opera (8.5 & 9.1), Safari (1.3 & 2.0), and Internet Explorer for Mac (5.2.3) are unaffected.
By way of demonstration, this page has the following conditional comment:
Visitors using Internet Explorer will have seen an alert as this page loaded. Users with other browsers will either see nothing (e.g. Safari), or a broken line of code at the top of the page, as everything after the greater-than operator is interpreted as being outside the comment and is rendered on the page (e.g. Firefox.)
Workarounds
There are two workarounds to the problem.
- Replace the decrement operator, so that
x--becomesx=x-1. But what self-resepcting geek wants to do that? - Change the script construct so that the decrement operator follows the value comparison step, e.g. replace the
do…whileloop with awhileorforloop (demonstration.) - Extract the code within the conditional comments to an external library.
Codicil: it's not a bug!
I'm very grateful to Alexander Clauss for clearing up my error in thinking that this was a bug. The decrement operator, or rather two hyphens, is recognised as a legitimate comment delimiter in SGML, and therefore browsers that adhere strictly to the standards will close the comment at this point.
The safest approach would be to remove commented JavaScript using the decrement operator to an external library. Unless you can suppress your geek nature and resort to x=x-1!