I generally prefer using PNGs to display images. They look better than GIFs because of the alpha-channel transparency, they compress much better than GIFs, and the color range is significantly wider and allows for smoother transitions and greater color precision. Plus, if you can live with the larger file size, they don’t have that lossy ghost pixelating of JPGs.
The problem is (what else?!) Internet Explorer, specifically version 6.X as it doesn’t support 24-bit PNG images with an alpha layer — which, of course, is what everyone wants on their web pages! So far, just about everybody and their grandmother creates “png.htc“, an IE-specific “behavior” component that fixes the alpha channel with an overlay. Then they apply a style class to the img (class="png"
) and then add a style to their stylesheet (.png { behavior: url('png.htc'); }
).
Since I often use Firefox for development and testing, I sometimes forget to look for those easily overlookable details in IE. I still use png.htc files, but now I include a small script that searches the DOM for PNGs and applies the behavior style automatically, activated with an onload action (<body onLoad="fixBrowsers();">
). It uses something called a Conditional Comment, a technique created by Microsoft, so it is sometimes praised and sometimes vilified.
Now I don’t have to remember to include the class for each image, and IE behaves the way I expect it to. Simple!
<script type="text/javascript">// <![CDATA[ function fixBrowsers() { /*@cc_on /*@if (@_jscript_version == 5.6) // add fix-alpha-layer behavior to all PNG images var array_images = document.getElementsByTagName("img"); var array_pngs = new Array(); var x; for (var i=0; i<array_images.length; i++) { x = array_images[i]; if (array_images[i].src.substring(array_images[i].src.length -3, array_images[i].src.length) == “png”) { array_pngs.push(x); } } for (var x=0; x<array_pngs.length; x++) { array_pngs[x].style.behavior = ”url(’png.htc’)”; } /*@end @*/ } // ]]></script>
Now, if only the fixBrowsers function would magically fix everything that is wrong with IE6. Now THAT would be the most sought-after JavaScript function ever!!
Author’s Note: By now, given that even IE7 and IE8 are hopefully soon to be on the distant horizon, pretty much anything to do with IE6 is now hopelessly obsolete, as is my snippet of code above.
For any of you still interested in developing for IE5 and IE6 for some strange reason, check out the awesome IE7-JS library which pretty much does magically fix everything wrong with IE5 and IE6. (Thanks to Brett for pointing out that library.)
Recent Comments