Tuesday 21 November 2006

CSS image flickering solved in IE

There has been a problem for many years that most of us have come across developing for Internet Explorer with background images "flickering" when the cursor is hovering over them. (here's an example). This is due to to Internet Explorer checking for a new version of the background image declared in the background-image css attribute when the mouse hovers over the tag. The flicker issue may also be accompanied with the hourglass flicking on or even no image flicker, but the hourglass flickers!

<script type="text/javascript" language="javascript">
/*@cc_on @*/
/*@if (@_jscript_version >= 4)
document.execCommand("BackgroundImageCache", false, true);
/*@end @*/
</script>

Essentially, if you include this script somewhere in your page (best towards the top) then it will resolve this problem. Banzai!

The comments with all the @ symbols are actually JScript (Microsoft's version of JavaScript) conditional commenting. In simple terms, only IE will see and execute this code. In more complex terms it means only the IE compiler will read and compile this code. This means that should you have large forks in your script - one to deal with IE and another to deal with any other browsers - you can often get large performance returns from using conditional compiling. There's a good article on javascriptkit.com about conditional compilation of JScript.

I can't take credit for this solution - MisterPixel came up with the goods looking into DHTML behaviours in IE with regards to another problem (a bit like Fleming discovering penicillin!).