png.js: PNG image replacement/support script

Getting PNG to work in Internet Explorer

Repeated from the SnowStorm write-up...

The primary benefit of PNG is alpha transparency, which makes for nice overlaying without the so-called "jaggies" that GIF suffers from. The downside is that IE does not "natively" support PNGs, you have to use a proprietary filter to get the transparency to work (among other things). For this reason I have been messing around with a PNG wrapper library which can add the IE crap while leaving the base HTML code as clean as possible - All that's required is a class declaration including "png" on said element (which can use GIF by default, which is what all buggy/non-PNG-supporting browsers will see.)

For anyone who may be interested, the relevant script can be found at the png.js project page. It has not been tested on a large number of configurations, presumably there are plenty of bugs remaining to be worked out. I believe it's a step in the right direction though for adding PNG support without having to sacrifice code structure, meaning or validity.

The following are simple examples of code that can be used with the PNG library currently in development, and will be "transformed" to PNG under supporting browsers:

<img src="image/foo.gif" alt="Foo image 1" />

<div style="background-image:url(image/foo.gif)">Foo image 1</div>

<style type="text/css">
#foo, div.foo {
background:transparent url(image/foo.gif) 0px 0px no-repeat;
}
</style>
<div id="foo">Foo image 1</div>
<div class="foo">Foo image 1</div>

The PNG wrapper can determine image source or background image URLs either directly from the attributes, or via the "rendered style" object (proprietary method under IE, and DOM under Mozilla). This is used to either transform the current element or replace it with a new element (in IE's case) containing the correct URL and/or filters needed to display the PNG correctly.

Using this method, older and non-PNG-supporting browsers should degrade gracefully as GIFs are provided "by default". To access the DOM after it has been parsed but before the body has loaded (important difference: the GIFs and other external sources have not yet loaded), the call to the script can be placed in an inline (CDATA-typed, so it's still valid) script block, eg.

<script type="text/javascript">
pngHandler = new PNGHandler();
</script>

Related links