Posts Tagged ‘Performance’

PNG Alpha Transparency – No Clear Winner

Jul ‘08 25

As a long time user of Adobe Photoshop, I missed the boat on a very important discovery in image optimization – PNG-8 supports full alpha transparency!

Alex Walker wrote a great article on PNG and included a nice example on creating PNG-8 images with a full alpha transparency layer with Fireworks – yes, Fireworks. Stoyan Stefanov points out this ability in his image optimization mistakes presentation as well. Thanks to you both for enlightening me!

Before Stoyan and Alex, I like probably many other thousands of Photoshop users believed, or still believe, that PNG-8 is identical to GIF, i.e. an all or nothing scenario when it comes to transparent pixels. In Photoshop, we are left with the usually bloated, heavy PNG-24 format that I typically steer folks away from.

However, in applying PNG-8 to my favorite PNG transparency techniques, I came to a different conclusion than Alex and Stoyan. This article shows there is no silver bullet when it comes to saving out PNGs (are you listening, Adobe?).

PNG Transparency Text Effects

One cool technique we can do with alpha PNGs are text effects, as detailed here by Nick La. The technique involves layering an empty element containing the horizontally tiled background gradient over system text.

Using this CSS and HTML, we can pull off the desired effect:

<style type="text/css">
	font: 45px 'arial rounded mt bold';
	margin: 0;
	position: relative;
	color: #f30;

.glossy-text b
	background: url(glossy-text-photoshop.png) repeat-x;
	position: absolute;
	width: 100%;
	height: 27px;
	top: 4px;
	display: block;
	_background: none;
	_filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='glossy-text-photoshop.png', sizingMethod='scale');

<div class="example">
<h2 class="glossy-text"><b></b>PNG Can Overlay Text</h2>

Here are the results…

PNG Can Overlay Text

And another using the same image, with blue text…

One Image for Every Heading!

The optimization win here is clear – use only 1 image across multiple headers to pull off a polished design for headings!

The PNG Image

I created the PNG image in Photoshop using a Gradient Fill layer. This gives us a fine deal of control over the gradient and the level of transparency to apply at each point. We can visually see how much transparency is applied by looking at the shade of the Opacity Stops. White is 0% Opacity (invisible), while black is 100% Opacity, or fully visible.

Photoshop Gradient Fill

Now, we will head on over to our trustworthy Save For Web tool, and notice how our PNG-8 doesn’t support full alpha, as usual.

PNG-8 PNG-24
Glossy Text Photoshop Png8  Glossy Text Photoshop Png24 

I will save out the PNG-24 version, which comes out to 156 bytes, not too bad at all. Let’s see if Fireworks and its PNG-8 format can do better.

Now, if you are new to Fireworks (like me), the workflow is a bit different than Photoshop. Let’s start by opening up our PNG-24 image saved out of Photoshop, and switching to the export Preview view.

Fireworks Export Preview View

The Export Preview is essentially the same thing as Photoshop’s Save for Web tool. Look over to the right in the above graphic at the Optimize and Align panel – those are the settings it’s using. Let’s update that to PNG-8, and the Alpha Transparency option.

Fireworks Optimize Align Png

To export the image, we can go to File…Export, but we can also see the expected KB in the lower-left corner of the panel, a file size of 248 bytes. After exporting, we see it was actually 238 bytes. (Adobe, why can’t this be completely accurate?)

Photoshop PNG-24, 156 bytes glossy text from photoshop
Fireworks PNG-8, 238 bytes glossy text from fireworks
Fireworks PNG-8 (dithered), 278 bytes glossy text dithered from fireworks

Now, this brings me pause, because the PNG-24 I saved out of Photoshop was a mere 156 bytes – 37% smaller in size! You can also clearly see that the Fireworks image is banding, which I would not expect to happen on such a low color image. I also dithered it, and it got larger and the pattern was still noticable.

It would seem that for this design purpose, the glossy text overlay, Photoshop’s PNG-24 is the better choice. My luck indeed!

Gradient Header Backgrounds

Similar in design to the text overlay image, the same finding is bound to hold true for gradient background techniques, right? Read on…

I’m going to create another Gradient Fill layer, and overlay a fade to white, and a fade to black over a layer filled with red. Notice I added a Color Stop in the center to ensure one side is white, and the other is black.

Glossy Background Gradient Fill

Just to be fancy, I will go ahead and add some fully opaque rounded corners using our selection tool. First, I’ll make a circle selection with a 10px diameter, giving us a 5px corner radius.

circle selection at the top left corner of the header

Next, we’ll add to the selection along the top and left hand sides of the circle selection.

same thing on the left hand side

Next, we’ll need to use Select…Inverse to flip the selection so we can fill it in.

menu select inverse

Using our pencil tool with at least a 5px radius, we fill in our rounded corner with white.

filled in with white

Notice that it also nicely anti-aliases against the layer below. For the other side, we’ll simply make a selection around it, and copy it over to the other side of the header.

copying the rounded corner

Move it over to the other side and do Edit…Transform…Flip Horizontal.

menu flip horizontal

And finally, position it in the right spot.

position the right corner

It is time to save out our PNG. Let’s go ahead and disable our layers and crop the image.

before diabling layers

after disabling the layers


And now for the PNG-24 vs. PNG-8 test.

Photoshop PNG-24, 399 bytes Glossy Background Photoshop Png24
Fireworks PNG-8, 397 bytes Glossy Background Fireworks Png8
Fireworks PNG-8 (dithered), 411 bytes Glossy Background Fireworks Png8

The tables have turned – PNG-8 wins by 2 bytes! However, notice again there is banding going on, which is bothersome to me for such a low color image. I played with all the settings I could in Fireworks to no avail, and the dither is larger in size and looks worse, so again I will have to hand this one to Photoshop’s PNG-24.

ImageOptim, a GUI PNG Tool

And then, I thought about messing around with some programs Alex mentioned in his article, the programs PNGQuant and PNGNQ. PNGQuant and PNGNQ take 32-bit or 24-bit PNG images and "quantize" them down to 8-bit, or PNG-8. Now, what sucks is that the tools are command line, although PNGQuant has a GUI version for Windows, it is difficult to install and doesn’t help OS X fans like myself and many other designers.

I couldn’t get either of these to work on OS X, because I am chobo and didn’t want to spend more then the 30 minutes I did trying to compile the source code on OS X.

In my Googling for GUIs, I discovered ImageOptim. Now, I have no clue what language the developer speaks, or what the tool does exactly, but if you want to help me translate for my readers, be my guest:

screen shot of imageoptim homepage with non english text

If I had to guess, it appears to try various PNG algorithms until it gets one that compresses the best. The tool is very user-friendly, and would fit nicely into any process as you simply drag and drop your files into its window, and it takes care of the rest.

To see how we fare, let’s take our full quality Photoshop PNG-24, and drop it in.

dragging png24 into imageoptim window

Viola! ImageOptim crunched our PNG-24 down to 355 bytes, a savings of 11%. Recall this is also smaller than our Fireworks PNG-8 (397 bytes).

imageoptim results window savings of 11%

The resulting file was smaller and identical to the original:

Photoshop PNG-24, 399 bytes Glossy Background Photoshop Png24
Fireworks PNG-8, 397 bytes Glossy Background Fireworks Png8
ImageOptim PNG, 355 bytes image optim png

Let’s go back and see if we can save anything from our Glossy Text image.

glossy text results showing no gain

Looks like we didn’t gain anything, oh well.

My one beef with ImageOptim is that I have no clue what it did. Did it throw away information? What program did it use, OptiPNG, PNGCrush, AdvPNG? And why is their logo of a man getting impaled by credit cards?

imageoptim logo

Okay, with that we’ll use the ImageOptim version of the PNG to complete our design, along with the following CSS and HTML, for those interested.

<style type="text/css">
	width: 250px;
	font-family: verdana;
	margin-bottom: 1em;
div.glossybg h2
	color: #fff;
	height: 32px;
	font: 18px/30px verdana;
	margin: 0;
	padding-left: 12px;
	background: #f30 url(glossy-background-imageoptim.png) repeat-x;
	text-align: center;
div.glossybg h2 b
	display: block;
	background: url(glossy-background-imageoptim.png) top right; /* Tricky bit! */
	background-color: #f30;
	padding-right: 12px;
	font-weight: normal;
div.glossybg h2.cold, div.glossybg h2.cold b
	background-color: #0066b3;
div.glossybg p
	border: 2px solid #ccc;
	border-width: 0 2px 2px;
	margin: 0;
	padding: 10px;

<div class="glossybg">
<h2><b>A Red Header</b></h2>
<p>Some text inside the skinny box.</p>
<div class="glossybg wide">
<h2 class="cold"><b>A Blue Header</b></h2>
<p>Some text inside the fat box.</p>

A Red Header

Some text inside the skinny box.

A Blue Header

Some text inside the fat box.

Notice the tricky bit of CSS indicated above. We are layering the image in <b> element of the header to pull off a rounded corner on the right side, allowing us to stretch the image to various widths, a favorite technique of mine.

Transparent Image Overlays

For my final experiment, I will create a banner header with a logo overlay, to demonstrate a more complex application of PNG.

We’re going to create a website banner for a fan site of a well known American politician. I downloaded some free artwork from his campaign website.

For our transparent overlay, I will need to cut him out of his poster and copy and paste him on a black background.

obama cut out

Then, we switch our document to Lab color mode.

lab color mode switch

This gives us a nice Lightness channel which we can use to create our overlay. In the Channels panel, select the Lightness channel, we’ll then make a selection using Command + Click (Windows Ctrl + Click).

select lightness channel and make a selection from it

This selects the light areas of the image, and also includes transparency information. Visually, you will see anything greater than 50% white with a marquee around it. If we wanted the dark pixels, we could simply select the inverse to obtain it.

This is also why we created him on a black background, to maintain the outline (transparent pixels are counted as white).

Now that I have my selection, I am going to switch back to RGB mode, create a new layer, and fill the selection in with white. I disabled the color layer to show the end result.

filled in the selection with white

We now have a layer with white transparency information in the shape of our political figure. Disable the black background, and save it out as Photoshop PNG-24. Export it through Fireworks and ImageOptim as outlined above.

Photoshop PNG-24
16764 bytes
Fireworks PNG-8
4542 bytes (73%)
Fireworks PNG-8 (dithered)
5265 bytes (69%)
Obama Photoshop Png24 Obama Fireworks Png8 Obama Fireworks Png8

ImageOptim was unable to gain any savings, so I didn’t include it. It seems as though ImageOptim doesn’t include a quantizer that will reduce the color palette like PNGQuant and PNGNQ, which is what we really want.

But I think we are finally getting somewhere on the Fireworks front. Our Fireworks PNG-8 was 73% smaller than our original PNG-24, though that banding is back (see his shoulder).

I exported another image out of Fireworks with a 100% dither, and think it looks much better. While a tad larger, I would recommend going with the dithered Fireworks PNG-8 image.

Let’s see how our finished product looks.

And if the boss said to make the background more patriotic, we can do so without affecting our transparent image.

What a catchy campaign slogan!

The Drop Shadow

I almost forgot the drop shadow! Well, I did forget it, I am editing this post just after I published it. Here is how a two color logo faired with a drop shadow.

Photoshop PNG-24

25232 bytes
Fireworks PNG-8

7150 bytes (72%)
Fireworks PNG-8 (dithered)

8615 bytes (66%)

23255 bytes (8%)
obama logo with photoshop fireworks fireworks dithered fireworks dithered

In this one, my vote is for the Fireworks PNG-8 dithered with a whopping savings of 66% and a decent looking shadow.

Let’s add a gradient to the logo, and see how that looks.

Photoshop PNG-24

42264 bytes
Fireworks PNG-8

11049 bytes (74%)
Fireworks PNG-8 (dithered)

13909 bytes (67%)
obama logo with photoshop fireworks fireworks dithered

At first glance, the dithered version would be my choice. However, if you look close enough, you see some odd dark specks here that just don’t belong. I tried to get rid of them in Fireworks, but my skills there are lacking. In this situation I would probably modify the source image to get the result I wanted. 1/2 point for effort, Fireworks.

PNG8 Graceful Degradation in IE 6

The final thing I’d like to echo with Stoyan and Alex about PNG8, is how gracefully it degrades in IE6.

Ie 6 Vs Ie 7 Png8 Transparency

Notice that all pixels that had transparency applied (the drop shadow) disappear, allowing for a graceful degradation in IE6. For most cases, this will be entirely acceptable and allow us to avoid the performance penalty and CSS hack associated with AlphaImageLoader, the traditional way to enable alpha transparency support in IE 6.

Take a look at how wide your IE6 audience is, and make a call on if it’s worth the design/performance tradeoff to fully support it.

Findings and Conclusions

At the end of the day, the score was +1 for Photoshop PNG-24, +1 for ImageOptim, and +2.5 for Fireworks PNG-8 (dithered). Because of Fireworks’ poor performance on the first two scenarios, there is no clear winner.

With my late discovery of Fireworks PNG-8, I went into this article thinking I would have the end all answer for saving out PNGs. If you’ve been reading, you know that it’s not quite so simple. We simply need better tools; preferably, one tool.

My final thought on a designer-friendly transparent PNG workflow:

  1. Save out your transparent PNG out of Photoshop as PNG-24, and take note of the size.
  2. Open the PNG-24 in Fireworks, and export it as PNG-8 with Alpha Transparency (play with the dither option), and take note of the size(s).
  3. Run your Photoshop PNG-24 through ImageOptim, and see if you saved anything.
  4. Make a final decision based on quality, size and longevity (e.g. how long will the image be around, how important is it?).

There seems to be a big gap on the GUI PNG tool side for saving out high quality, low file size PNGs. While command line tools exist, they are not a realistic answer for designers who haven’t ever launched a terminal window, and for developers who don’t have the time or patience to compile source code.

I want to encourage Adobe to look at the available open source PNG tools and get them into Photoshop CS4′s Save For Web, where it belongs.

Until that happens, I am going to have to respectfully disagree with Stoyan and Alex that PNG-8 is the clear winner, as in 2 of the important use cases above, it wasn’t.


Beating Blocking JavaScript: Asynchronous JS

Jul ‘08 23

MSN is now implementing a technique for loading JavaScript in a way that doesn’t stall the rendering of the document. They use Dynodes, a technique I also recommend for loading functionality on demand so it only consumes bandwidth when it is needed.

JavaScript Blocks Everything

To see the problem, view a Pagetest waterfall report of pretty much any website today, or see this recent run of Notice that 1 second is spent downloading and executing JavaScript, one at a time.

waterfall graphic of aol javascript blocking rendering

One by one, folks! This is how all browsers load JavaScript (unless the defer attribute is used in IE) when called from your standard HTML <script> element.

However, viewing a waterfall report of MSN, we can see that they call 3 JavaScript files (dap.js, hptr.js, and hp.js) asynchronously, and allow the subsequent CSS files to load right away.

waterfall graphic of msn javascript not blocking

Had their scripts loaded in the standard way, dap.js, hptr.js, and hp.js would delay the page for 1.4 seconds!

Loading JavaScript Asynchronously

MSN is using standard DOM functions to create and append a script element to the HTML document’s <head> element. This technique, originally coined as Dynodes, is encapsulated in a JavaScript loader, much like the one used by JS frameworks such as Dojo.

We downloaded and formatted the HTML source code so you can have a closer look at it. Start on line 297 which kicks off a process to a function aptly named JS:


Note that it is passed in two URLs defined back on Lines 13-19:


The JS function kicks off a method that pulls down these two scripts. Take a look at line 130 to get to the heart of this technique:

var c=g.createElement("script");

The <script> element (c) is appended to the <head> element (p), as defined back on line 113.

MSN also appears to be closely monitoring the load of all the scripts called by JS, in case something happens during the process. Event handlers are set on readystatechange, error, and load to stop the polling process (fired every 100ms) once the script is finished.

Their code is quite obfuscated and difficult to follow, but you can look for the timeout function on line 125. There also appears to be an optional parameter to kill the process after a specified period of time.

JS Loader Prototype

We designed a JS Loader Prototype (not nearly as fancy as MSN’s) that illustrates the benefits of this technique, and tested behaviors in IE and Firefox.

In our prototype (we strongly suggest you view the source now), the code is organized into 4 sections:

  • JavaScript #1 and #2 are called from a <script> block in the <head> using our JS Loader function.
  • JavaScript #3 and #4 follow next, called by the JS Loader in a <script> block in the <body>.
  • JavaScript #5 and #6 are called after some text again by the JS Loader, from a second <script> block in the <body>.
  • Finally, #7 and #8 are loaded in the traditional, HTML <script> element fashion.

In Internet Explorer, the script files queued up normally and the screen was not blocked for any period of time (until #7 and #8). Notice a very short Start Render time in our test run at Pagetest, and JS loading as fast as HTTP1.1′s 2 connection per domain limit will allow it:

waterfall chart of js loader prototype in ie showing full asynchronous load

In Firefox, however, any content below the next inline HTML <script> section is blocked until the scripts from the previous inline HTML <script> section called by the loader are complete. You have to see it to believe it!

waterfall chart of firefox blocking until all js has download in each script block

Notice in the above chart, within each script block both JavaScript must fully load before the next script block is allowed to start processing. The takeaway here is to include as many JS Loader calls as possible in one script block.

We developed a workaround for this issue by including a timeout delay before calling the script. This allows Firefox to continue rendering like IE and Safari, and affords the fastest possible download. See the updated JS Loader Prototype for Firefox here.

waterfall of updated prototype showing that firefox no longer blocks other scripts

We put a longer delay on the first script (10 seconds) so you can see that Firefox no longer waits until the script block has completed before loading others. The important bit of code looks like this:

	// If you want to call IE and Safari straight up without the delay, uncomment this.
	// ('Firefox')) ? js = setTimeout("artz.create('"+url+"')", 0) : artz.create(url);
	js = setTimeout("artz.create('"+url+"')", 0);
	s = artz.ce('script');
	s.type = 'text/javascript';
	s.src = url;

You will be pleased to know that Safari renders much like IE, with the added benefits of 4 open socket connections!

waterfall shot of safari with 4 open socket connections

Hopefully the benefits to this approach are clear. With a large site like MSN faithfully using Dynodes for their scripts, it might just be the time to standardize on this approach.

Race Condition Challenges

Not so fast! (pardon the pun) There are some additional considerations we will need to think through when moving in this direction.

  • JavaScript functions in the external scripts may not be available when inline HTML JavaScript functions call for them.
  • Along the same lines, even if Script A is called before Script B, Script B may finish and execute before Script A.
  • DOM elements may not yet be available in the HTML should an external script need them to hook events, access data from, etc.

In tackling the above, we would first recommend following the Progressive Enhancement approach, and work to completely eliminate inline HTML JavaScript function calls. The external scripts can latch any events needed on to links, buttons, etc., once they are ready.

While race conditions may still exist, a way to solve this is using the setInterval function to initialize your functions where you know a race condition may exist.

function id(id){return document.getElementById(id)}

var oranges =
	init: function()
			alert('We have oranges!');
			// We may proceed with orange code!

oranges_init = setInterval("oranges.init()", 100);

We recommend using a period of 100ms to go easy on the CPU, and still feel instantaneous to users. To see this code in action, have a look at our ID Polling Prototype.


External scripts loaded that include the infamous document.write method executed by the script will cause problems with this technique. Be sure to wrap it in a function and call it from the HTML if you decide to head down this path. We hope that by now, you have thrown this ancient tool away.

Advertising vendors…this means you!

Final Thoughts

This technique has been on the back shelf for some time due to the tricky Firefox and race condition issues.

That said, if we are careful, and with MSN proving its value, now just may be the time to adopt Dynodes as a standard JavaScript loading practice.

Leave us a comment with your thoughts, questions, and concerns, and post links to implementations that leverage this!


Optimizing Web Performance with AOL Pagetest

Jul ‘08 10

In this screencast, I walk through how to analyze your site using the reports generated by AOL Pagetest, and explain why and how to go about addressing your pressing performance issues. Come for the tool demo, and stay to learn about the anatomy of an HTTP request, the importance of CDN’s and keep-alives, and a handy Apache module to concatenate CSS and JavaScript. Leave me feedback so I can improve it, and enjoy!

Please index me, experiment!

“It’s called reading, you know, top to bottom, left to right. A group of words together is called a sentence. Take Tylenol for any headaches, Midol for any cramps.” — Richard Hayden