The Problem
Download
| Download: | sm-iepng.js |
| Version: | |
| Released: |
In Internet Explorer 6 and earlier, PNG support is very limited. One of the most important features of PNG its support for alpha transparency. It looks like IE version 7 will finally support alpha transparency in PNGs without workarounds like this!
Example
The following image is displayed on red, green, and blue backgrounds. On IE 6 and earlier the background colors don't show through.
Actually, Internet Explorer does have support for alpha transparency just not directly via the <img> tag. You can display a PNG as the background of pretty much any element by using Internet Explorer's proprietary AlphaImageLoader.
Example
Using the AlphaImageLoader we can use the following code to display a PNG properly in Internet Explorer:
<img src="/images/spacer.png" width="31" height="31" alt="" style="filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=/images/dynamic/smiley.jsp, sizingMethod=scale);"/>
If we were only concerned with displaying PNG images in IE this might work even though it takes a lot of effort. The problem with this approach is it excludes browsers which already have great support for PNG and that is unacceptable.
The Solution
Fortunately ScriptingMagic.com has an easy solution using JavaScript!
- Download sm-iepng.js and save it on your web server.
- Include the JavaScript file you just downloaded in the head of your page. Example:
<script type="text/javascript" src="/javascript/sm-iepng.js" defer="defer" charset="ISO-8859-1"></script>. - Add sm:iepng="true" to any <img> or <input type="image"> which you would like to be affected.
Example
<script type="text/javascript" src="/javascript/sm-iepng.js" defer="defer" charset="ISO-8859-1"></script>
...
<img src="/images/dynamic/smiley.jsp" sm:iepng="true" alt=""/>
This method makes it much easier to add PNG alpha support for Internet Explorer and it doesn't affect any other browsers. It also handles situations where you change the image url such as during mouseover effects!
Example
Notes
You should only include sm-iepng.js once per page and it should appear in the <head> section. Also make sure it appears exactly as shown above with the "defer" attribute set. That instructs IE to load the JavaScript file when the DOM is complete. If you wait for the <body>'s onload event your images may flicker as they change from the default IE PNG handler to the AlphaImageLoader.