Sunday, March 28, 2010

Different Approach to the Usual CSS Sprite to Reduce HTTP Requests




I just found this little tidbit today. If you ever have a problem with too many HTTP requests, this could be a solution for you over a CSS sprite. I’m using this approach for my CSS backgrounds that are simple small icons. I would not recommend this approach for anything much larger. FYI: IE8 limits URIs to max length of 32KB.

To help with this approach, you’ll need a couple tools. Here are the few I found:

Obviously, you can always write your own :)

So, this is what I wanted:

image

My original CSS looked like this:

a#createarticle {padding-left: 20px; background: url(/i/ico-addarticle.png) no-repeat center left}

This code will make two HTTP requests, one for the stylesheet and another for the icon. (assuming the above code is in a stylesheet, which in my case, it is)

To eliminate the additional HTTP request, I changed my CSS to look like this:

#createarticle {padding-left: 18px; background: url(data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEASABIAAD/2wBDAAYEBAQFBAYFBQYJBgUGCQsIBgYICwwKCgsKCgwQDAwMDAwMEAwODxAPDgwTExQUExMcGxsbHCAgICAgICAgICD/2wBDAQcHBw0MDRgQEBgaFREVGiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICD/wAARCAAQAA8DAREAAhEBAxEB/8QAFwAAAwEAAAAAAAAAAAAAAAAAAQIHCP/EACUQAAICAQIEBwAAAAAAAAAAAAECAwQSAAUGERMhFCIjMTJSgf/EABYBAQEBAAAAAAAAAAAAAAAAAAAEBf/EABwRAQABBAMAAAAAAAAAAAAAAAARAQISIRMxQf/aAAwDAQACEQMRAD8A0nUoVpKMEhhjZ2jRmZkUkkqOZJI0DVl8NajEXlimOEkPIBQwQtknL2+HcaA0b1JKVdHsRo6xoGVnUEEL3BGgktniveJ6lafZbtmfjYSP19mJ6kYbEB/QzKqqKz4nH9+2TzXzqcprpHnXzt//2Q%3D%3D) no-repeat center left}

This might look intimidating, but it’s really pretty simple. You simply replace the “/i/ico-addarticle.png” in the first sample with the generated base64 from one of the tools mentioned above.

To get the base64, I used A Blue Star because I wanted to upload an image and get the base64, but you could also use the greywyvern.com and that’s what I’ll walk through now.

So I’ll grab an icon from famfamfam.com (which is where I get almost all my icons) and paste the URL on the greywyvern.com site.

Step 1: Grab URL
Paste it into the URI textbox on greywyvern.com like this:

image

Step 2: Generate Results
Click Submit Query & you’ll get this:

image

Step 3: Copy & Paste Results
Copy ALL the textarea and paste it into either the src of an img object or into the url of a CSS background attribute.

If you like your CSS to be readable and don’t want to deal with looking at base64, then I would stick to the CSS sprite, but I thought this method was cool. Especially for icons next to hrefs that don’t change a lot. However, I think the configuration for this is much simpler than a CSS sprite and having to deal with the different margins, widths, etc that come along with a CSS sprite :)

Thanks for reading!

kick it on DotNetKicks.com

blog comments powered by Disqus
Related Posts Plugin for WordPress, Blogger...