[譯]谷歌Web性能優化系列:HTTP 緩存(中英)

原文連接(需越牆)developers.google.com/web/fundame…

原文做者:Dave Gash   譯者:西樓聽雨javascript

此做是谷歌開發者網站關於Web性能優化的入門系列文章之一,該系列的其餘篇章,及對應的高級系列文章,本人後續會持續發佈,歡迎你們關注。(轉載請註明出處)
css

When someone visits a website, everything the site needs to display and operate has to come from somewhere. All the text, images, CSS styles, scripts, media files, and so on must be retrieved by the browser for display or execution. You can give the browser choices about where it can retrieve a resource from, and that can make a big difference in your page's load speed.html

當某人訪問一個網站時,網站須要展示和操縱的東西確定是從某些地方來的。全部的文本,圖片,CSS樣式,腳本,媒體文件,等等必定都是由瀏覽器負責展示和執行的。你能夠告訴瀏覽器一些能夠獲取這些資源的地方,而選擇的地方不一樣會致使頁面的加載速度有很大的區別。java

The first time a browser loads a web page, it stores the page resources in the HTTP Cache. The next time the browser hits that page, it can look in the cache for resources that were previously fetched and retrieve them from disk,
often faster than it can download them from the network.web

瀏覽器在第一次加載一個網頁時,會將頁面上的資源保存在HTTP緩存中;下次,當瀏覽器訪問這個頁面時,瀏覽器能夠從緩存中將這些以前已經獲取到的資源直接從硬盤上獲取,這比從網絡獲取要快不少。瀏覽器

While HTTP caching is standardized per the Internet Engineering Task Force (IETF) specifications, browsers may have multiple caches that differ in how they acquire, store, and retain content. You can read about how these caches vary in this excellent article, A Tale of Four Caches.緩存

」HTTP 緩存「是一項已經標準化的規範,是由互聯網工程任務組(Internet Engineering Task Force (IETF))制定的,規定瀏覽器能夠擁有多種緩存,而不一樣的緩存,其獲取、存儲,和留存方式也不同。關於這些緩存的區別,這有一篇很是棒的文章,《四種類型的緩存的故事》(A Tale of Four Caches),你能夠看下。性能優化

Of course, every first-time visitor to your page arrives with nothing yet cached for that page. Even repeat visitors may not have much in the HTTP cache; they might have manually cleared it, or set their browser to do so automatically, or forced a fresh page load with a control-key combination. Still, a significant number of your users may revisit your site with at least some of its components already cached, and that can make a huge difference in load time. Maximizing cache usage is critical to speeding up return visits.bash

雖然,每一個第一次到達你頁面的訪客,在此以前是沒有緩存的;即使是回訪客也可能沒有多少HTTP緩存;由於他們可能已經手動清除掉了,或者讓瀏覽器自動清除掉了;他們也可能經過控制鍵(ctrl)組合強制刷新了頁面。但不論如何,仍是有可觀數量的用戶會回訪你的網站,那個時候,他們已經至少有一些組件是以前已經緩存起來了的,這就能夠帶來巨大的加載時間的不一樣。最大化利用緩存對於回訪客的回訪頁面加載速度的提高是相當重要的。服務器

Enabling Caching 開啓緩存

Caching works by categorizing certain page resources in terms of how frequently or infrequently they change. Your site's logo image, for example, might almost never change, but your site's scripts might change every few days. It's beneficial to you and your users to determine which types of content are more static and which are more dynamic.

緩存是基於經過按變更頻繁程度來對頁面資源進行的分類而工做的。例如,網站的Logo 圖片,它幾乎從不改動,但腳本文件可能每隔幾天就會有改動。所以,對每種類型的文件的靜態、動態的性質進行評估是很是有幫助的。

It's also important to remember that what we think of as browser caching may in fact take place at any intermediate stop between the original server and the client-side browser, such as a proxy cache or a content delivery network (CDN) cache.

咱們對於瀏覽器緩存的認識一樣重要,事實上,緩存可能發生在任何處於服務器和客戶端之間的中間件節點上,例如代理服務的緩存和內容分發網絡(CDN)中的緩存。

Cache Headers 緩存相關的頭部

Two main types of cache headers, cache-control and expires, define the caching characteristics for your resources. Typically, cache-control is considered a more modern and flexible approach than expires, but both headers can be used simultaneously.

有兩種主要的緩存相關的頭部,Cache-Control 和 Expires,能夠用來定義資源的緩存屬性。一般,Cache-Control 被認爲是比 Expires 更現代化、更靈活的方式,不過其實兩種頭部是能夠同時使用的。

Cache headers are applied to resources at the server level -- for example, in the .htaccess file on an Apache server, used by nearly half of all active websites -- to set their caching characteristics. Caching is enabled by identifying a resource or type of resource, such as images or CSS files, and then specifying headers for the resource(s) with the desired caching options.

經過緩存頭部來設置資源的緩存特性是在服務器上進行的——例如,Apache 服務器上的 .htaccess 文件,已經被接近一半的活躍網站所使用;緩存是經過爲一個資源或者一類資源——例如圖片和 CSS 文件——設置指望的緩存選項來啓用的。

Cache-control

You can enable cache-control with a variety of options in a comma-delimited list. Here is an example of an Apache .htaccess configuration that sets caching for various image file types, as matched by an extension list, to one month and public access (some available options are discussed below).

應用 Cache-Control 頭部時,你能夠經過逗號分隔的列表來配置它的各個選項,下面是 Apache 中的 .htaccess 配置文件的一個例子,它經過文件後綴名列表匹配多種類型的圖片文件,來爲其設置了一個最長生存週期爲一個月,及(緩存器)權限爲公開(public)的緩存。

<filesMatch ".(ico|jpg|jpeg|png|gif)$">
 Header set Cache-Control "max-age=2592000, public"
</filesMatch>
複製代碼

This example sets caching for styles and scripts, resources that are probably more likely to change than the images, to one day and public access.

下面這個列子,爲樣式和腳本文件——相對圖片文件更新頻率更高的一類資源——設置了生存週期爲一天,權限爲公開的緩存。

<filesMatch ".(css|js)$">
 Header set Cache-Control "max-age=86400, public"
</filesMatch>
複製代碼

Cache-control has a number of options, often called directives, that can be set to specifically determine how cache requests are handled. Some common directives are explained below; you can find more information at the Performance Optimization section and at the Mozilla Developer Network.

Cache-Control 擁有一系列的選項,咱們一般稱之爲 directives他們能夠用來指定如何處理對緩存資源的請求。下面是一些經常使用指令的講解;更多的信息能夠前往對應性能優化章節(Performance Optimization section) 和 Mozilla 開發者網絡(Mozilla Developer Network)瞭解。

  • no-cache: Somewhat of a misnomer, specifies that content can be cached but, if so, it must be re-validated on each request before being served to a client. This forces the client to check for freshness but allows it to avoid downloading the resource again if it has not changed. Mutually exclusive with no-store.

  • no-cache: 其實這個名稱並不恰當,它的意思是說,能夠對內容進行緩存,但若是確實進行了緩存,那麼每次請求以前必須(向服務器)進行一次驗證。雖然它強制了客戶端對資源進行「新鮮程度「檢查,但若是資源並未發生變更則可避免再次下載。與 no-store 選項互斥。

  • no-store: Indicates that the content actually cannot be cached in any way by any primary or intermediate cache. This is a good option for resources that may contain sensitive data, or for resources that will almost certainly change from visit to visit. Mutually exclusive with no-cache.

  • no-store: 指示內容不該該以任何形式,在主要的緩存或中間件中被緩存起來。適用於那些包含敏感信息,或者那些幾乎每次訪問都會發生變更的數據。與 no-cache 互斥。

  • public: Indicates that the content can be cached by the browser and by any intermediate caches. Overrides the default private setting for requests that use HTTP authentication. Mutually exclusive with private.

  • public: 指示瀏覽器能夠對內容進行緩存,也能夠被任意中間件進行緩存。指定後,會覆蓋默認是 private 的 HTTP 驗證請求爲 public 。與 private 指令互斥。

  • private: Designates content that may be stored by the user's browser, but may not be cached by any intermediate caches. Often used for user-specific, but not particularly sensitive, data. Mutually exclusive with public.

  • private: 指示內容能夠被瀏覽器進行緩存,但其餘任意中間件不該該緩存。一般用在特定於用戶,但又不是特別敏感的數據上。與 public 指令互斥。

  • max-age: Defines the maximum time that the content may be cached before it must be revalidated or downloaded again from the original server. This option generally replaces the expires header (see below) and takes a value in seconds, with a maximum valid age of one year (31536000 seconds).

  • max-age: 指定被緩存的內容向服務從新驗證或再次下載的以前的最大生存週期,這個選項一般用於代替 Expires 頭(請看下文介紹),接受以秒爲單位的值,最大值爲一年(即31536000秒)


Expires Caching 過時型緩存

You can also enable caching by specifying expiration, or expiry, times for certain types of files, which tell browsers how long to use a cached resource before requesting a fresh copy from the server. The expires header just sets a time in the future when the content should expire. After that point, requests for the content must go back to the original server. With the newer and more flexible cache-control header, the expires header is often used as a fallback.

另外,你也能夠經過設置一個過時時間的形式來設置指定文件類型的緩存,以此告訴瀏覽器緩存資源在從新獲取一份新的以前能夠被使用多長時間。Expires 頭即可以經過設置一個將來的時間點,來設置內容(緩存)的過時時間。在那個時間點以後,對該內容的請求必須回到服務器上。Expires 頭一般被做爲替補方案與更新、更靈活的 cache-control 頭一塊兒使用。

Here's an example of how you might set up caching in the .htaccess file on an Apache server.

下面是 Apache 服務器上在 .htaccess 文件中怎樣設置(這種類型的)緩存的例子:

## EXPIRES CACHING ##
ExpiresActive On
ExpiresByType image/jpg "access plus 1 year"
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/gif "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType text/css "access plus 1 month"
ExpiresByType application/pdf "access plus 1 month"
ExpiresByType text/x-javascript "access plus 1 month"
ExpiresByType application/x-shockwave-flash "access plus 1 month"
ExpiresByType image/x-icon "access plus 1 year"
ExpiresDefault "access plus 2 days"
## EXPIRES CACHING ##
複製代碼

(來源: GTmetrix)

As you can see, different types of files have different expiry dates in this example: images don't expire for a year after access/caching, while scripts, PDFs, and CSS styles expire in a month, and any file type not explicitly listed expires in two days. The retention periods are up to you, and should be chosen based on the file types and their update frequency. For example, if you regularly change your CSS, you might want to use a shorter expiry, or even none at all, and let it default to the two-day minimum. Conversely, if you link to some static PDF forms that almost never change, you might want to use a longer expiry for them.

你能夠看到,在此例中,不一樣類型的文件設置了不一樣了過時時間:圖片類型的文件(訪問或者緩存以後)的過時時間爲一年;腳本,PDF,CSS樣式文件的過時時間爲一個月;其餘未顯式地列出來的文件類型則爲兩天。具體的留存週期(retention periods)取決於你,而你應該基於文件的類型以及他們的更新頻率來作出選擇。例如,若是你常常修改你的CSS文件,那麼你應該使用一個較短的過時時間,或者甚至不作設置,就採用默認的「兩天」。反之,若是你引用的是一些幾乎從不改變的靜態PDF表單,那麼你應該使用一個較長的過時時間。

Tip: Don't use an expiry greater than one year; that's effectively forever on the internet and, as noted above, is the maximum value for max-age under cache-control.

提示:不要設置超過一年的過時時間,這在因特網上至關於永遠;和前面說的 cache-control 中的 max-age 同樣,這是它的最大值。


Summary 總結

Caching is a reliable and low-hassle way to improve your pages' load speed and thus your users' experience. It is powerful enough to allow sophisticated nuances for specific content types, but flexible enough to allow easy updates when your site's content changes.

緩存是一種對於提高頁面加載速度進而提高用戶體驗的可靠、低成本的方式。雖然對指定文件類型的精細控制它已經很強大了,但對於內容變更的輕易更新卻還不是很靈活。

Be assertive with caching, but also be aware that if you later change a resource that has a long retention period, you may inadvertently deprive some repeat visitors of newer content. You can find a great discussion of caching patterns, options, and potential pitfalls in Caching Best Practices and Max-age Gotchas.

對於緩存咱們要信任,但同時也要意識到,若是某個資源擁有一個較長的緩存週期,而以後你又對其進行了修改,那麼,無心中你可能就剝奪了某些回訪者看到新內容的機會。關於緩存的模式(patterns),選項(options),以及可能的一些陷阱,在《最佳緩存實踐和Max-age的要點Caching Best Practices and Max-age Gotchas)》中作了很好的探討,你能夠找來看看。

相關文章
相關標籤/搜索