# How HTTP/2 Is Changing Web Performance Best Practices
# HTTP/2正給Web性能最佳實(shí)踐帶來(lái)怎樣的影響?
原文地址:https://dzone.com/articles/how-http2-is-changing-web-performance-best-practic
HTTP/2 debuted in May 2015, and since its inception, it'sbeen influencing web performance best practices. Here's a look at binaryframes, latency reduction, and possible cons of HTTP/2.
HTTP/2于2015年5月正式推出。自誕生以來(lái),它就一直在影響著網(wǎng)絡(luò)性能最佳實(shí)踐。在本篇博文中,我們將討論HTTP/2的二進(jìn)制幀、延遲削減以及潛在利弊。
Clay Smith
2016年02月09日
The Hypertext Transfer Protocol (HTTP) underpins the WorldWide Web and cyberspace. If that sounds dated, consider that the version of theprotocol most commonly in use, HTTP 1.1, is nearly 20 years old. When it was[ratified back in 1997](https://www.ietf.org/rfc/rfc2068.txt) , floppy drivesand modems were must-have digital accessories and Java was a new, up-and-comingprogramming language. Ratified in May 2015, HTTP/2 was created to address somesignificant performance problems with HTTP 1.1 in the modern Web era. Adoptionof HTTP/2 has increased in the past year as browsers, Web servers, commercialproxies, and major content delivery networks have committed to or releasedsupport.
超文本傳輸協(xié)議(簡(jiǎn)稱(chēng)HTTP)正是萬(wàn)維網(wǎng)與網(wǎng)絡(luò)空間創(chuàng)建的基石。盡管HTTP聽(tīng)起來(lái)已經(jīng)有些過(guò)時(shí),畢竟該協(xié)議中使用最廣泛的版本--HTTP1.1,現(xiàn)如今已快迎來(lái)它的第二十個(gè)年頭。[時(shí)光回溯到1997年,HTTP1.1剛剛出現(xiàn)的年代](https://www.ietf.org/rfc/rfc2068.txt),當(dāng)時(shí),軟驅(qū)與調(diào)制解調(diào)器還是PC設(shè)備的必備周邊產(chǎn)品,Java也僅僅是一個(gè)剛剛嶄露頭角的、前途一片光明的編程語(yǔ)言。而今,2015年5月,HTTP/2正式亮相,致力于解決HTTP1.1在現(xiàn)代網(wǎng)絡(luò)時(shí)代下無(wú)法應(yīng)對(duì)的某些重大性能難題。過(guò)去一年以來(lái),越來(lái)越多的瀏覽器、Web服務(wù)器、商用代理以及主要內(nèi)容交付網(wǎng)絡(luò)開(kāi)始支持HTTP/2。
Unfortunately for people who write code for the Web, transitioningto HTTP/2 isn’t always straightforward and a speed boost isn’t automaticallyguaranteed. The new protocol challenges some common wisdom when buildingperformant Web applications and many existing tools—such as debuggingproxies—don’t support it yet. This post is an introduction to HTTP/2 and how itchanges Web performance best practices.
遺憾的是,對(duì)于負(fù)責(zé)編寫(xiě)Web代碼的開(kāi)發(fā)人員而言,HTTP/2的過(guò)渡工作并不簡(jiǎn)單,所謂的速度的提升也不會(huì)自行出現(xiàn)。如何才能采用這個(gè)新型協(xié)議打造高性能Web應(yīng)用,該怎樣處理那些尚不支持該協(xié)議的現(xiàn)有工具——例如debug代理工具,這些問(wèn)題對(duì)所有人來(lái)說(shuō)仍是一個(gè)挑戰(zhàn)。今天的博文將向您介紹HTTP/2,以及其如何改變Web性能的最佳實(shí)踐。
#Binary frames: The ‘fundamental unit’ of HTTP/2
#二進(jìn)制幀:HTTP/2的“基本單位”
One benefit of HTTP 1.1 (over non-secure connections, atleast) is that it supports interaction with Web servers using text in a telnetsession on port 80: typing GET / HTTP/1.1 returns an HTML document on most Webservers. Because it’s a text protocol, debugging is relatively straightforward.
HTTP 1.1的一大優(yōu)勢(shì)(至少相較于非安全連接而言)在于其支持在端口80的telnet會(huì)話中利用文本與Web服務(wù)器進(jìn)行交互:在大多數(shù)Web服務(wù)器上輸入GET/ HTTP/1.1,都能返回一個(gè)HTML文檔。由于這是一項(xiàng)文本協(xié)議,因此其debug工作相對(duì)簡(jiǎn)單。
Instead of text, requests and responses in HTTP/2 arerepresented by a stream of binary frames, described as a “basic protocol unit”in the [HTTP/2 RFC](https://tools.ietf.org/html/rfc7540). Each frame has a typethat serves a different purpose. The authors of HTTP/2 realized that HTTP 1.1will exist indefinitely (the [Gopherprotocol](https://en.wikipedia.org/wiki/Gopher_%28protocol%29) still is outthere, after all). The binary frames of an HTTP/2 request map to an HTTP 1.1request to ensure backwards compatibility.
相對(duì)于HTTP1.1這個(gè)文本協(xié)議,HTTP/2中的請(qǐng)求與響應(yīng)則通過(guò)二進(jìn)制幀流的形式來(lái)表現(xiàn),我們將其稱(chēng)為[HTTP/2RFC](https://tools.ietf.org/html/rfc7540)中的“基本協(xié)議單位”。每一幀都擁有自己的類(lèi)型,用于實(shí)現(xiàn)不同的作用??紤]到HTTP1.1將會(huì)“永遠(yuǎn)”存在(畢竟[Gopher協(xié)議](https://en.wikipedia.org/wiki/Gopher_%28protocol%29)都還在用呢?。?,因此HTTP/2的作者們要求,HTTP/2請(qǐng)求的二進(jìn)制幀都必須被映射到HTTP1.1請(qǐng)求上去,從而確保其向下兼容的能力。
There are some new features in HTTP/2 that don’t map to HTTP1.1, however. Server push (also known as “cache push”) and stream reset arefeatures that correspond to types of binary frames. Frames can also have apriority that allows clients to give servers hints about the priority of someassets over others.
當(dāng)然,HTTP/2當(dāng)中也有一些其他新特性,無(wú)法映射至HTTP 1.1。例如,服務(wù)器推送(也叫“緩存推送”)和流重置都是利用二進(jìn)制幀類(lèi)型實(shí)現(xiàn)的新特性。幀可以具備一個(gè)優(yōu)先級(jí)排序,通過(guò)客戶端可以向服務(wù)器發(fā)送排序,從而優(yōu)先處理一部分資產(chǎn)類(lèi)別。
Other than using [Wireshark 2.0](https://www.wireshark.org/),one of the easiest ways to actually see the individual binary frames is byusing the net-internals tab of Google Chrome (typechrome://net-internals/#http2 into the address bar). The data can be hard tounderstand for large Web pages. [Rebecca Murphey](https://github.com/rmurphey)helpfully wrote [a useful tool for displaying itvisually](https://github.com/rmurphey/chrome-http2-log-parser) in the commandline.
除了使用[Wireshark 2.0](https://www.wireshark.org/)之外,對(duì)個(gè)別二進(jìn)制幀進(jìn)行實(shí)際查看的最為簡(jiǎn)便的方法之一就是利用谷歌Chrome瀏覽器的net-internals標(biāo)簽(在瀏覽器地址欄中輸入chrome://net-internals/#http2)。由于理解大型網(wǎng)頁(yè)的數(shù)據(jù)通常比較困難,[RebeccaMurphey](https://github.com/rmurphey)特意編寫(xiě)了[一款極為實(shí)用的可視化工具](https://github.com/rmurphey/chrome-http2-log-parser),從而將其顯示在命令行中。
Additionally, the protocol used to fetch assets can bedisplayed in the Chrome Web developer tools—right click on the column headerand select “Protocol”:
除此之外,這個(gè)用于獲取資產(chǎn)的協(xié)議還能夠顯示在Chrome Web的開(kāi)發(fā)者工具當(dāng)中--只需右鍵點(diǎn)擊列標(biāo)題,接著選擇“協(xié)議”即可:

*Viewing protocol types in Google Chrome developer tools.*
*在谷歌Chrome開(kāi)發(fā)者工具當(dāng)中查看協(xié)議類(lèi)型。*
All of the HTTP/2 requests in this listing use a secureconnection over Transport Layer Security (TLS). All major browsers requireHTTP/2 connections to be secure. This is done for a practical reason: anextension of TLS called Application-Layer Protocol Negotiation (ALPN) letsservers know the browser supports HTTP/2 (among other protocols) and avoids anadditional round-trip. This also helps services that don’t understand HTTP/2,such as proxies—they see only encrypted data over the wire.
這里列出的所有HTTP/2請(qǐng)求都使用通過(guò)傳輸層安全(TLS)建立的安全連接。各主流瀏覽器都要求HTTP/2連接是安全的。這樣做是有切實(shí)理由的:TLS的一套稱(chēng)為應(yīng)用層協(xié)議協(xié)商(ALPN)的擴(kuò)展,讓服務(wù)器知道瀏覽器支持HTTP2(在各種其他協(xié)議中),從而避免了額外的數(shù)據(jù)往來(lái)。這也能保住那些無(wú)法解讀HTTP/2的服務(wù),例如代理——只看得見(jiàn)傳輸線路上的加密數(shù)據(jù)。
#Reducing latency with multiplexing
#多路復(fù)用減少延遲
A key performance problem with HTTP 1.1 is latency, or thetime it takes to make a request and receive a response. This issue has becomemore pronounced as the number of images and amount of JavaScript and CSS on atypical Web page continue to [increase](http://httparchive.org/trends.php) .Every time an asset is fetched, a new TCP connection is generally needed. Thisrequirement is important for two reasons: the number of simultaneous open TCPconnections per host is limited by browsers and there’s a performance penaltyincurred when establishing new connections. If a physical Web server is faraway from users (for example, a user in Singapore requesting a page hosted at adata center on the U.S. East Coast), latency also increases. This scenario isnot uncommon— [one recentreport](http://www.nextgov.com/big-data/2016/01/70-percent-global-internet-traffic-goes-through-northern-virginia/124976/)says that more than 70% of global Internet traffic passes through the unmarkeddata centers of Northern Virginia.
HTTP 1.1的一大問(wèn)題是延遲,換而言之就是它花在提出請(qǐng)求和接受響應(yīng)上的時(shí)間。隨著典型網(wǎng)頁(yè)中圖片數(shù)量、JavaScrip和CSS的使用量不斷[增加](http://httparchive.org/trends.php),這個(gè)問(wèn)題日益嚴(yán)重。每獲取一項(xiàng)資產(chǎn),通常都得新建一個(gè)TCP連接。這種需求因?yàn)閮蓚€(gè)理由很重要:每臺(tái)主機(jī)能同時(shí)打開(kāi)的TCP連接數(shù)受瀏覽器的限制;新建連接都會(huì)引發(fā)性能損失。如果物理服務(wù)器里用戶很遠(yuǎn)(如:一位新加坡用戶向美國(guó)東海岸數(shù)據(jù)中心請(qǐng)求一個(gè)頁(yè)面),延遲會(huì)變多。這不是罕見(jiàn)的情況——[近期一份報(bào)告](http://www.nextgov.com/big-data/2016/01/70-percent-global-internet-traffic-goes-through-northern-virginia/124976/)表示全球70%以上的互聯(lián)網(wǎng)流通都會(huì)通過(guò)北佛吉尼亞一些不知名的數(shù)據(jù)中心。
HTTP 1.1 offers different workarounds for latency issues,including pipelining and the Keep-Alive header. However, pipelining was neverwidely implemented and the Keep-Alive header suffered from head-of-lineblocking: the current request must complete before the next one can be sent.
HTTP 1.1提供了多種方案以解決延遲問(wèn)題,包括通道傳輸與Keep-Alive協(xié)議頭。然而,通道傳輸從未被廣泛采納過(guò),而Keep-Alive協(xié)議頭則飽受線頭阻塞的困擾:只有在當(dāng)前請(qǐng)求必須徹底完成后,下一請(qǐng)求才能被發(fā)送出去。
In HTTP/2, multiple asset requests can reuse a single TCPconnection. Unlike HTTP 1.1 requests that use the Keep-Alive header, therequests and response binary frames in HTTP/2 are interleaved and head-of-lineblocking does not happen. The cost of establishing a connection (the well-known“three-way handshake”) has to happen only once per host. Multiplexing isespecially beneficial for secure connections because of the performance costinvolved with multiple TLS negotiations.
在HTTP/2當(dāng)中,多條資產(chǎn)請(qǐng)求可以重復(fù)利用單一TCP連接。與使用Keep-Alive協(xié)議頭的HTTP1.1請(qǐng)求不同,HTTP/2的請(qǐng)求與響應(yīng)二進(jìn)制幀以交錯(cuò)方式進(jìn)行,線頭阻塞問(wèn)題也不復(fù)存在。建立連接的成本(即著名的的‘三方握手’)在每臺(tái)主機(jī)上只進(jìn)行一次。多路復(fù)用對(duì)于安全連接來(lái)說(shuō)尤為重要,因?yàn)槎啻蜹LS協(xié)商方案的性能成本將會(huì)得到顯著提高。

*Requests for multiple assets on a single host use a singleTCP connection in HTTP/2.*
*在HTTP/2中,單一主機(jī)內(nèi)的多資產(chǎn)請(qǐng)求只使用單一TCP連接。*
#Implications for Web Performance: Goodbye Inlining,Concatenation, and Image Sprites?
#Web性能影響:與內(nèi)聯(lián)、級(jí)聯(lián)及圖像精靈說(shuō)再見(jiàn)?
HTTP/2 multiplexing has broad implications for frontend Webdevelopers. It removes the need for several long-standing workarounds that aimto reduce the number of connections by bundling related assets, including:
HTTP/2多路復(fù)用對(duì)前端Web開(kāi)發(fā)人員造成了深遠(yuǎn)的影響。長(zhǎng)久以來(lái),人們用盡方法,試圖通過(guò)捆綁相關(guān)資產(chǎn)來(lái)削減連接的數(shù)量,而現(xiàn)在這一切都不需要了。人們嘗試過(guò)的方法包括:
- **ConcatenatingJavaScript and CSS files:** Combining smaller files into
a larger file toreduce the total number of requests.
- **Image spriting:**Combining multiple small images into one larger image.
- **Domainsharding:** Spreading requests for static assets across several domains toincrease the total number of open TCP connections allowed by the browser.
- **Inliningassets:** Bundling assets with the HTML document
source, includingbase-64 encoding images or writing JavaScript code
directly insidescript tags.
- **JavaScript與CSS文件級(jí)聯(lián):**將多個(gè)小文件合成一個(gè)大文件,從而降低總體請(qǐng)求數(shù)量。
- **圖像精靈:**將多個(gè)小圖像合成一張大圖像。
- **域名碎片:**在多個(gè)域之間發(fā)送靜態(tài)資產(chǎn)請(qǐng)求,從而增加瀏覽器所能允許的總體開(kāi)放TCP連接數(shù)量。
- **內(nèi)聯(lián)資產(chǎn):**將資產(chǎn)同HTML文檔源綁定,包括base-64編碼圖片,以及直接寫(xiě)入script標(biāo)簽的JavaScript代碼。
With unbundled assets, there is greater opportunity toaggressively cache smaller pieces of a Web application. It’s easiest to explainthis with an example:
因?yàn)椴恍枰俳壎ㄙY產(chǎn),我們就有了更多機(jī)會(huì),將Web應(yīng)用程序中的小片段加以緩存。舉個(gè)例子可以幫我們更好的理解這一點(diǎn):

*A concatenated and fingerprinted CSS file unbundles intofour smaller fingerprinted files.*
*一個(gè)級(jí)聯(lián)且指紋驗(yàn)證型CSS文件被解綁為四個(gè)較小的指紋驗(yàn)證文件。*
A common concatenation pattern has been to bundle stylesheetfiles for different pages in an application into a single CSS file to reducethe number of asset requests. This large file is then fingerprinted with an MD5hash of its contents in the filename so it can be aggressively cached bybrowsers. Unfortunately, this approach means that a very small change to thevisual layout of the site, like changing the font style for a header, requiresthe entire concatenated file to be downloaded again.
常見(jiàn)的級(jí)聯(lián)模式是將樣式表文件進(jìn)行綁定,將單一應(yīng)用程序內(nèi)的不同頁(yè)面合到一個(gè)單一的CSS文件之內(nèi),以減少資產(chǎn)請(qǐng)求的數(shù)量。這個(gè)大文件隨后會(huì)通過(guò)文件名內(nèi)的MD5哈希值進(jìn)行指紋校驗(yàn),確保其能夠被瀏覽器主動(dòng)緩存。遺憾的是,這樣的解決方案意味著,當(dāng)站點(diǎn)的可視化布局中出現(xiàn)了任何一點(diǎn)小的改變,如標(biāo)題字體的改變,都需要重新下載整個(gè)級(jí)聯(lián)文件。
When smaller asset files are fingerprinted, significantamounts of JavaScript and CSS components that don’t change frequently can becached by browsers—a small refactor of a single function no longer invalidatesa massive amount of JavaScript application code or CSS.
當(dāng)對(duì)小型資產(chǎn)文件進(jìn)行指紋校驗(yàn)時(shí),相當(dāng)一部分的JavaScript與CSS組件都不會(huì)頻繁產(chǎn)生變動(dòng),因此可以被瀏覽器緩存--也就是說(shuō),任何一個(gè)單一功能的小型重構(gòu),不會(huì)再導(dǎo)致大量的JavaScript應(yīng)用程序代碼或者CSS失效。
Lastly, deprecating concatenation can reduce frontend buildinfrastructure complexity. Instead of having several pre-build steps thatconcatenate assets, they can be included directly in the HTML document assmaller files.
最后,級(jí)聯(lián)機(jī)制的消失能夠降低前端構(gòu)建基礎(chǔ)的復(fù)雜性。與以往通過(guò)一些列預(yù)置步驟來(lái)級(jí)聯(lián)資產(chǎn)不同,現(xiàn)在它們作為小型文件,可以直接被放入HTML文檔中。
#Potential Downsides of Using HTTP/2 in the Real World
#真實(shí)使用HTTP/2的潛在弊端
Optimizing only for HTTP/2 clients potentially penalizesbrowsers that don’t yet support it. Older browsers still prefer bundled assetsto reduce the number of connections. As of February 2016,[caniuse.com](http://caniuse.com/) reports [global browser support of HTTP/2 at71%](http://caniuse.com/#feat=http2). Much like dropping Internet Explorer 8.0support, the decision to adopt HTTP/2 or go with a hybrid approach must be madeusing relevant data on a per-site basis.
僅僅針對(duì)支持HTTP/2客戶端而做出的各類(lèi)優(yōu)化,意味那些不支持HTTP/2的瀏覽器可能因此陷入不利境地。那些“有年頭”的瀏覽器們?nèi)匀粌A向于綁定資產(chǎn),以此降低連接數(shù)量。截至2016年2月,[caniuse.com](http://caniuse.com/)網(wǎng)站報(bào)道稱(chēng),[全球?yàn)g覽器中能夠支持HTTP/2的占比71%](http://caniuse.com/#feat=http2)。與瀏覽器們?cè)?jīng)決定放棄支持IE8.0一樣,支持HTTP/2或者采取某種混合作業(yè)的方式,這樣的決定只能根據(jù)各個(gè)網(wǎng)站自身的相關(guān)數(shù)據(jù)來(lái)做出。
As described in [a post by Kahn AcademyEngineering](http://engineering.khanacademy.org/posts/js-packaging-http2.htm)that analyzed HTTP/2 traffic on its site, unbundling a large number of assetscan actually increase the total number of bytes transferred. With[zlib](http://www.zlib.net/), compressing a single large file is more efficientthan compressing many small files. The effect can be significant on an HTTP/2site that has unbundled hundreds of assets.
正如[卡恩工程院的博文](http://engineering.khanacademy.org/posts/js-packaging-http2.htm)所述,他們?cè)治隽似渚W(wǎng)站上的HTTP/2流量,事實(shí)上,拆分大量資產(chǎn)會(huì)增加所傳輸字節(jié)的總量。而使用[zlib](http://www.zlib.net/)壓縮單一大型文件,比壓縮多個(gè)小型文件要更有效率。對(duì)于擁有成百上千解綁資產(chǎn)的HTTP/2站點(diǎn)來(lái)說(shuō),這種效應(yīng)更為顯著。
Using HTTP/2 in browsers also requires assets to bedelivered over TLS. Setting up TLS certificates can be cumbersome for theuninitiated. Fortunately, open source projects such as [Let’sEncrypt](https://letsencrypt.org/) are working on making certificateregistration more accessible.
在瀏覽器中使用HTTP/2還要求我們通過(guò)TLS進(jìn)行資產(chǎn)交付。對(duì)于菜鳥(niǎo)們來(lái)說(shuō),設(shè)置TLS證書(shū)就是個(gè)煩人的活。幸運(yùn)的是,諸如[Let’sEncrypt](https://letsencrypt.org/)的開(kāi)源項(xiàng)目正努力讓證書(shū)注冊(cè)工作變得更加便捷。
#A Work in Progress
#仍在進(jìn)行中的工作
Most users don’t care what application protocol your siteuses—they just want it to be fast and work as expected. Although HTTP/2 hasbeen officially ratified for almost a year, developers are still learning bestpractices when building faster websites on top of it. The benefits of switchingto HTTP/2 depend largely on the makeup of the particular website and whatpercentage of its users have modern browsers. Moreover, debugging the newprotocol is challenging and easy-to-use developers tools are still underconstruction.
大部分用戶并不在意你的站點(diǎn)用了啥協(xié)議——他們只想要它速度快,運(yùn)行如人預(yù)期。雖然HTTP/2已經(jīng)正式被批準(zhǔn)快一年了,開(kāi)發(fā)人員還在學(xué)習(xí)如何利用它來(lái)建立更快速網(wǎng)站的最優(yōu)實(shí)踐。換用HTTP/2的好處更多取決于具體站點(diǎn)的制作和多大比例的用戶使用現(xiàn)代的瀏覽器。再有就是,調(diào)試新協(xié)議很有挑戰(zhàn)性,更易用的開(kāi)發(fā)工具也在研制中。
Despite these challenges, HTTP/2 adoption is growing.According to researchers scanning popular Web properties, [the number of topsites that use HTTP/2 isincreasing](http://isthewebhttp2yet.com/measurements/adoption.html), especiallyafter [CloudFlare](https://www.cloudflare.com/) and [WordPress](https://wordpress.com/)announced their support in late 2015. When considering a switch, it’s importantto carefully measure and monitor asset- and page-load time in a variety ofenvironments. As vendors and Web professionals educate themselves on the implicationsof this massive change, making decisions from real user data is critical. Inthe midst of a [website obesitycrisis](http://idlewords.com/talks/website_obesity.htm), now is a great time tocut down on the total number of assets regardless of the protocol.
雖然有這些挑戰(zhàn),HTTP/2的采納度在增加。根據(jù)研究人員掃描流行網(wǎng)站屬性的結(jié)果,[排名前列的站點(diǎn)中使用HTTP/2的一直在增加](http://isthewebhttp2yet.com/measurements/adoption.html),特別是[CloudFlare](https://www.cloudflare.com/)和[WordPress](https://wordpress.com/)2015年宣布提供支持之后。考慮轉(zhuǎn)換的時(shí)候,很重要的一點(diǎn)是仔細(xì)測(cè)量資源和頁(yè)面在不同環(huán)境下加載的時(shí)間。供應(yīng)商和專(zhuān)業(yè)網(wǎng)站人員都熟悉了大量轉(zhuǎn)換背后的含義,從真實(shí)用戶數(shù)據(jù)中做出判斷才是關(guān)鍵的。在[網(wǎng)站臃腫危機(jī)](http://idlewords.com/talks/website_obesity.htm)之時(shí),這是一個(gè)無(wú)視協(xié)議削減資源數(shù)量的好時(shí)機(jī)。
In Part 2 of this series on HTTP/2, we’ll focus on practicalimplementation details of HTTP/2 and how to enable it on your server and debugreal traffic.
在這一關(guān)于HTTP/2系列的第二部分中,我們會(huì)聚焦如何在服務(wù)器上實(shí)現(xiàn)HTTP/2和調(diào)試真是網(wǎng)絡(luò)通信的具體實(shí)現(xiàn)細(xì)節(jié)。
This article was written by Clay Smith, with contributionsof technical feedback and invaluable suggestions by Jeff Martens, ProductManager for New Relic Browser, and Web performance expert Andy Davies.
本文作者為Clay Smith,同時(shí)New Relic瀏覽器的產(chǎn)品經(jīng)理JeffMartens和Web性能專(zhuān)家AndyDavies都給出了技術(shù)反饋和極為寶貴的建議。