Home > 软件|测试 > WEB程序性能优化之CSS Sprites

WEB程序性能优化之CSS Sprites

10月 27th, 2008

前几天看了篇关于CSS Sprites的文章(mg12),这样一种追求完美的技术,不仅仅是体现开发者的满足感,更重要的是为服务器节省了很可观的资源,目前这个web程序盛行的年代,这个技术应该是每个关注性能的人都应该了解的。作为一个测试人,你可能不需要去精通这个技术如何使用,但是在某些时候,你或许可以建议公司的产品使用它。

CSS Sprites简单来讲就是:将小图标拼在一个图片文件里. 然后在 CSS 中通过 background-position 定位访问图标。CSS Sprites对于访问量很大的网站来讲好处显而易见。我们知道基于http协议,服务器上每一个独立的资源(图片,css,js等)浏览器都要通过一个get请求来获取。如果网站上只有10个图标,那每一个访问者初次访问时都要发送10个get请求来获取这十个图标,但是如果使用CSS Sprites,就能把请求数降低到原来的十分之一,也许每一个get消耗的时间非常短,但是这个时间和一个主流的门户网站每天的浏览量做个乘法运算,这个数字也相当了得。所以我觉得这个技术不应该只是程序员完美主义的表现,而是应该做为一个web程序开发的标准。

目前国外的一些网站都开始广泛使用此技术,Google,Yahoo,Facebook等,Goole用的最炉火纯青,不过它主要是用此技术用到了制作美观的效果上,而Yahoo和Facebook确实是为了改善服务器性能。

我这里做了一个小小的示例以供观者能更详细的了解这个小精灵。先看下面这个图片:

csssprites实例图

这张图片中有两个小图标是连在一起的,下面只需要使用以下css调整位置就可以只调用其中那个一张图片,或者调用两张图片,并且随意调整图标位置,我只是简单的用DIV显示一下:

<div style=”background-position: -10px -48px; width: 28px; height: 19px”>&nbsp;</div>

这一句就是显示那个问号,只要你的页面用到问号的统统这样调用就可以了,

<div style=”background-position: -10px -10px; width: 28px; height: 19px”>&nbsp;</div>

调用第一个图标,显示效果见:Demo

此文主要把CSS sprites当成一种性能优化的手段,若要了解更详细的CSS sprites细节,可以参考以下网站:

中文资料 http://realazy.org/blog/2007/10/08/css-sprites/

英文资料 http://www.sitepoint.com/blogs/2007/07/05/css-using-percentages-in-background-image/

在线制作工具 http://www.csssprites.com/ (本站Demo在此网站生成)

其他资源:

What Are CSS Sprites?

http://www.peachpit.com/articles/printerfriendly.aspx?p=447210&rl=1

CSS Sprites: Image Slicing’s Kiss of Death

http://www.alistapart.com/articles/sprites/

CSS Sprites Generator

http://www.csssprites.com/

Fast Rollovers Without Preload

http://wellstyled.com/css-nopreload-rollovers.html

JavaScript Sprite Animation Using jQuery

http://www.sitepoint.com/blogs/2007/07/20/javascript-sprite-animation-using-jquery/

http://www.sitepoint.com/blogs/2007/07/05/css-using-percentages-in-background-image/

How to create CSS sprites

http://fatagnus.com/how-to-create-css-sprites/

Creating Rollover Effects with CSS Sprites

http://www.devarticles.com/c/a/Web-Style-Sheets/Creating-Rollover-Effects-with-CSS-Sprites/

Building a Dynamic Banner with CSS Sprites

http://www.devarticles.com/c/a/Web-Style-Sheets/Building-a-Dynamic-Banner-with-CSS-Sprites/

CSS Sprites and IE/Win Flicker Issue

http://www.brajeshwar.com/2006/css-sprites-and-iewin-flicker-issue/

css用法测试工具:CSS tests and experiments

http://www.brunildo.org/test/index.html

scott 软件|测试

  1. 10月 27th, 2008 at 09:07 | #1

    恩 需要好好学习了。

  1. No trackbacks yet.
You must be logged in to post a comment.