TransPNG
From xbe wiki
To support transparent PNG files in Internet Explorer < 7, a lot of hacking is necessary. There are a lot of variants to solve this problem, but most of them lack in some stuff..
- They waste cpu time onload massively when using with a lot of pictures - like 300-400 imgs..
- They need some custom css tag for each png (what do with existing projects?)
- They use the shitty htc-behavior-hack..
Contents |
[edit] Cached transPNG solution (the ultimate)
For most cases, a caching mechanism is needed. Take tabular data with "action icons" in each row (like copy/delete icons). Most of the PNG-hacks out there don't take into account that most of the images on the page have the same src - thus kinda cache would be helpful.
This is my approach.. include the following javascript in a file like "transpng.js", wherever you like it..
var IS_PNG = /\.png$/i;
theCache = new Array();
theCache[0] = new Object();
function correctPNG() // correctly handle PNG transparency in Win IE 5.5 or higher.
{
imgs = $A(document.images);
spacerImg = new Image();
spacerImg.src = '/images/spacer.gif';
i = 0;
imgs.each(function(img) {
if( IS_PNG.test(img.src) ) {
origSrc = img.src;
if(typeof(theCache[0][origSrc]) == "undefined") {
imgHeight = img.height;
imgWidth = img.width;
if (imgHeight != 0) {
img.src = spacerImg.src;
img.style.width = imgWidth+'px';
img.width = imgWidth;
img.style.height = imgHeight+'px';
img.height = imgHeight;
img.runtimeStyle.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' + origSrc + '", sizingMethod="scale")'
}
theCache[0][origSrc] = img.cloneNode();
i++;
}else{
var theParent = img.parentNode;
var newObj = theCache[0][origSrc].cloneNode();
newObj.runtimeStyle.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' + img.src + '", sizingMethod="scale")'
img.parentNode.replaceChild(newObj, img);
}
}
});
}
Event.observe(window, 'load', function() {
correctPNG();
});
[edit] Explanation
I can't make it out actually why this is so much faster with much alike images than any other solution i've seen before (and i searched alot). Note that this actually just makes sense with much images alike..
It also seems that the time consuming part is not the applying of the filter, it seems to be other stuff ;-)
[edit] Requirements / Usage
Include scriptaculous before the transpng.js inside the page. At the end, it should look this way in your head..
<html> <head> <!-- other head stuff --> <script src="/js/scriptaculous/prototype.js" type="text/javascript"></script> <script src="/js/scriptaculous/scriptaculous.js" type="text/javascript"></script> <!--[if lt IE 7]> <script type="text/JavaScript" src="/js/transpng.js"></script> <![endif]--> </head> <body> <!-- content --> </body> </html>
[edit] Customizing
Keep in mind that you may have to change the path to your spacer.gif ! ;-)
