Posts Tagged ‘transparent’

Cross-Browser Transparent Image Display

Tuesday, December 18th, 2007

Problem:
I am currently working on a map web site (www.eghlim.com) - city map of Tehran, Iran. The main problem is the big loading time. One thing I found, was the way we handled png images containing transparent parts: Firefox draws them properly, given the background image source, but IE needs a ‘filter’, griven the background image ‘null’.
The previous solution was to search for *.png images by javascript on page load, checking the browser and creating appropriate objects. As shown below:

var sheets = document.styleSheets;
Browser.Detect();  // Browser.js is provided at the end of the post   

if (sheets && Browser.Name == 'Internet Explorer' && Browser.Version <= 6 && Browser.OS == "Windows")
   for (i = 0; i < sheets.length; i++)
      if(sheets[i].rules)
         for(j=0; j < sheets[i].rules.length; j++)
            if(sheets[i].rules.item(j).style.backgroundImage.indexOf(".png") != -1)
            {
               var imageUrl = sheets[i].rules.item(j).style.backgroundImage;
               imageUrl = imageUrl.substring(imageUrl.indexOf('(../') + 4, imageUrl.lastIndexOf(')'));
               sheets[i].rules.item(j).style.backgroundImage = "none";
               sheets[i].rules.item(j).style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + imageUrl + "', sizingMethod='scale')";
            }

The result was disappointing! IE freezes until the scripts are done, and then renders the whole page in 1 sec.

Answer:
I searched for 2 long days to find a better solution, tested several ways and finally found a nice work-around, By Rafael Lima. The essence is to use a css hack to define different styles for different browsers. In this case (showing a transparent png image in Firefox and IE):

.TabMenu .Left
{
   filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='Images/Tab/Left.png', sizingMethod='scale'); background-image:url("../Images/Tab/Left.png");
}
.win.ie .TabMenu .Left
{
   background-image:none;
}

Just adding css_browser_selector.js (as little as 10 lines of code) makes this possible. Fast and clean, isn’t it?

Mahdieh

P.S. Browser.js