网站性能提升最佳实践一

https://developer.yahoo.com/performance/rules.html?guccounter=1#csslink

  • Content
  • Server
  • Cookie
  • CSS
  • JavaScript
  • Images
  • Mobile

原文从七个方面总结网站性能提升。

本篇总结Content方面。

Make Fewer HTTP Requests 减少HTTP请求

减少页面的组件数量,可以减少HTTP请求数量。

减少页面组件的方法:

  • 精简页面设计

  • 不简化设计的情况下:

    • 文件组合(js文件放到一个里面,css文件放到一个里面)
  • CSS Sprites:背景图片合并成一张,利用css属性设置各个部分到相对应的页面

  • 将内联图片放到css文件中( Combining inline images into your cached stylesheets is a way to reduce HTTP requests and avoid increasing the size of your pages ?How ? ( Todo: find demo

Reduce DNS Lookups 减少DNS查询

减少网站的主机名(hostnames),可以减少DNS查询次数

但是减少网站主机名会减少页面的并发下载量

Trade-off:Avoiding DNS lookups cuts response times, but reducing parallel downloads may increase response times.

Guide:Split components across at least two but no more than four hostnames.

Avoid Redirects 避免网站重定向

最经常发生的重定向:应该加/的地方没有加/

重定向可以用来从旧网站跳转到新网站

重定向也可以用来连接网站的不同部分、根据特定情况让用户跳转

解决办法:

  • 如果两个网站在同一个服务器,使用 Alias and mod_rewrite

  • 如果是网站换了个新域名,创建一个CNAME (a DNS record that creates an alias pointing from one domain name to another),结合Alias or mod_rewrite

Make Ajax Cacheable 缓存Ajax请求

异步不等于即时

优化异步请求:

  • 缓存Ajax请求

何时使用旧的响应,何时发送新的请求?

This could be done by adding a timestamp to the address book Ajax URL indicating the last time the user modified her address book, for example, &t=1190241612. If the address book hasn’t been modified since the last download, the timestamp will be the same and the address book will be read from the browser’s cache eliminating an extra HTTP roundtrip. If the user has modified her address book, the timestamp ensures the new URL doesn’t match the cached response, and the browser will request the updated address book entries.

Postload Components

非必须的组件延迟加载,比如一些js代码、用户点击后才显示的内容、文件夹里面的图片

确保页面正常工作,然后通过一些延迟加载的脚本增强页面上的体验,比如动画、拖放

Preload Components

利用计算机的闲置时间,预加载将来需要的内容

  1. 无条件的

    只要打开某网站就加载一些额外的组件。

    打开google.com,总会预加载之后搜索界面的图片

  2. 有条件的

    搜索框输入内容就会预加载内容

  3. 预期中的

    上线网站新设计时预加载可以不影响用户体验

Reduce the Number of DOM Elements

页面tag数量

1
document.getElementsByTagName('*').length

只有在语义上有意义时,才使用<div>( 因为它总会添加一行

有多少个DOM元素才算多呢?

检查其他类似的页面,然后比较。

Split Components Across Domains

拆分组件可以最大限度地实现并行下载

确保使用的域名数量不超过2-4个,因为DNS查询惩罚

例子:

将HTML文件和动态内容托管在www.example.org,并在static1.example.org和static2.example.org上拆分部署静态组件

Minimize Number of iframes

<iframe> 优点:

  • Helps with slow third-party content like badges and ads
  • Security sandbox
  • Download scripts in parallel

<iframe> 缺点:

  • Costly even if blank
  • Blocks page onload
  • Non-semantic

Avoid 404s

HTTP请求是很昂贵的,提出HTTP请求,得到一个无用的响应(即404 Not Found)是完全没有必要的,而且会拖慢用户体验,没有任何好处。

Particularly bad is when the link to an external JavaScript is wrong and the result is a 404. First, this download will block parallel downloads. Next the browser may try to parse the 404 response body as if it were JavaScript code, trying to find something usable in it.