從web現狀談及前端性能優化

從web現狀談及性能優化

原文出處:《Karolina Szczur: The State of the Web》javascript

性能優化指南
The Internet is growing exponentially, and so is the Web platform we create. Often though we fail to reflect on the greater picture of connectivity and contexts the audience of our work might find themselves in. Even a short glance at the state of the World Wide Web shows that we haven’t been building with empathy, situation variability awareness, let alone performance in mind.
現在網絡發展迅猛,這對咱們構建的互聯網平臺要求也更高。而咱們卻疲於反思用戶與咱們之間的聯繫。這就說明,咱們在開發時,並無站在用戶的角度上換位思考,更別談性能優化。php

So, what is the state of the Web today?
那麼,互聯網現狀如何?css

Only 46% of 7.4 billion people on this planet have access to the Internet. The average network speed caps at unimpressive 7Mb/s. More importantly, 93% of Internet users are going online through mobile devices — it becomes inexcusable to not cater to handhelds. Often data is more expensive than we’d assume — it could take anywhere from an hour to 13 hours to purchase 500MB packet (Germany versus Brazil; for more intriguing stats on connectivity head to Ben Schwarz’s Beyond the Bubble: The Real World Performance).
據統計,全球只有3億多人能接觸到互聯網,但網速平均只有7mb/s,關鍵的是,其中3億是經過移動端瀏覽。勢必,咱們開發時必須考慮這部分人羣的需求。並且,數據也比咱們想象中的要貴,有數據指出,咱們能夠在1-13個小時內就花掉500MB流量(參考德國和巴西----想要更多關於用戶與互聯網之間聯繫的有趣統計,能夠看:https://building.calibreapp.c...)。html

Our websites aren’t in a perfect shape either — the average site is the size of original Doom game (approx. 3 MB) (please note that for statistical accuracy medians should be used, read Ilya Grigorik’s excellent The 「Average Page」 is a myth. Median site size is currently at 1.4MB). Images can easily account for 1.7 MB of bandwidth and JavaScript averages at 400KB. This isn’t a problem specific to the Web platform only. Native applications aren’t better; remember that time you had to download 200 MB to get unspecified bug fixes?
並且,咱們搭建的網站也並不完善——平均一個網站(計算首屏加載)的大小和國外經典桌面遊戲Doom game1的大小差很少(大約3MB)(注意這裏計算出的平均值,參考Ilya Grigorik’s excellent The 「Average Page」 is a myth,目前通常網站首屏加載大約要1.4MB),其中加載圖片須要1.7MB,javascript須要400KB。不只在pc端有這個問題,手機原生應用也好不到哪去,還記得你必須花200MB流量來更新app修復未知缺陷嗎?前端

As technologists often we find ourselves in the position of privilege. With up-to-date, high-end laptops, phones and fast cable Internet connection, it becomes all to easy to forget this isn’t the case for everyone (actually, it’s true for very few).
If we’re building the web platform from the standpoint of privilege and lack of empathy, it results in exclusionary, subpar experiences.
How can we do better by designing and developing with performance in mind?
做爲技術人員,咱們擁有絕對的優點。用最新、高配置的電腦和手機,網速也超快,這讓咱們很容易認爲普羅大衆也是這樣(事實上,是不多不多)。
構建網絡平臺時,若是咱們安於開發特權、缺少用戶同理心,將會致使極糟的用戶體驗。
那麼,在設計和開發時,怎樣才能作到性能優化呢?java

優化全部資源

Optimising all assets
One of the most powerful, but under-utilised ways to significantly improve performance starts with understanding how the browser analyses and serves assets. It turns out that browsers are pretty great at discovering resources while parsing and determining their priority on the fly. Here’s where the critical request comes in.
A request is critical if it contains assets that are necessary to render the content within the users’ viewport.
For most sites, it’d be HTML, necessary CSS, a logo, a web font and maybe an image. It turns out that in many cases, dozens of other, irrelevant at the time assets are requested instead (JavaScript, tracking codes, ads, etc.). Luckily, we’re able to control this behaviour by carefully picking crucial resources and adjusting their priority.
要想顯著地提高性能,最有效但也容易被忽視的方法就是了解瀏覽器如何解析資源。已被證實,瀏覽器善於查找資源而且解析後快速肯定資源加載的優先級順序。那麼什麼資源優先級高呢?這裏有關於critical request的來源:
判斷一個請求是關鍵性請求,就看它是否包含用於渲染用戶可見內容的資源
對於大多數網站來講,關鍵性請求是請求html文件、必要的css、logo、字體文件和圖片,在加載完這些文件後,再選擇加載其它非決定性的文件(JavaScript、統計代碼、廣告...)。所以,咱們可經過區分關鍵資源並調整加載的優先級來實現性能優化。node

With <link rel='preload'> we’re able to manually force assets’ priority to High ensuring that desired content will be rendered on time. This technique can yield significant improvements in Time to Interactive metric, making optimal user experience possible.
方法一:爲link標籤設置rel='preload'屬性,手動設置該資源優先加載,來確保所指望的內容及時呈現。這種技術能夠顯着改善「交互時間」,使最佳用戶體驗成爲可能。
clipboard.pngreact

Critical requests still seem like a black box for many, and the lack of shareable materials doesn’t help to change that. Fortunately, Ben Schwarz published an incredibly comprehensive and approachable article on the subject — The Critical Request. Additionally, check Addy’s Preload, Prefetch and Priorities in Chrome.
關鍵性請求對於大多數人來講彷佛仍是個盲區,可共享資源的缺少也沒有改變這一點。幸虧,本·施瓦茨(Ben Schwarz)發表了一篇關於關鍵性請求的文章,文章很是全面且易懂。另外,Addy也有一篇文章《在Chrome中的預加載,預取和優先級》webpack

clipboard.png

General performance checklistgit

  1. Cache aggressively
  2. Enable compression
  3. Prioritise critical assets
  4. Use content delivery networks

廣泛的性能優化方式

  1. 積極地使用緩存
  2. 使用壓縮
  3. 優先加載關鍵性請求
  4. 使用內容傳送網絡CDN

優化圖片

Optimising images
Images often account for most of a web page’s transferred payload, which is why imagery optimisation can yield the biggest performance improvements. There are many existing strategies and tools to aid us in removing extra bytes, but the first question to ask is: 「Is this image essential to convey the message and effect I’m after?」. If it’s possible to eliminate it, not only we’re saving bandwidth, but also requests.
圖片一般佔網頁傳輸的大部分有效載荷,所以圖片優化能夠帶來最大的性能提高。有許多現有的策略和工具能夠幫助咱們刪除額外的字節,但咱們要考慮的第一個問題是:「這張圖片對於傳達個人信息和效果是否相當重要」。作好了圖片優化,能夠爲用戶節省不少帶寬。

In some cases, similar results can be achieved with different technologies. CSS has a range of properties for art direction, such as shadows, gradients, animations or shapes allowing us to swap assets for appropriately styled DOM elements.
在某些狀況下,不必定非得用圖片,能夠經過不一樣的代碼方式實現相同的效果。CSS具備一系列屬性設置藝術樣式,例如陰影,漸變,動畫或形狀,這些屬性能夠把資源轉換爲適當風格的DOM元素。

選擇正確的格式

Choosing the right format
If it’s not possible to remove an asset, it’s important to determine what format will be appropriate. The initial choice falls between vector and raster graphics:
若是不可能刪除資源,肯定哪一種合適的格式很重要。首選矢量圖或柵格圖:

Vector: resolution independent, usually significantly smaller in size. Perfect for logos, iconography and simple assets comprising of basic shapes (lines, polygons, circles and points).
Raster: offers much more detailed results. Ideal for photographs.
矢量:分辨率獨立,一般尺寸很小。適用於logo,icon和一些由基本形狀(線,多邊形,圓和點)組成的圖片。
柵格:提供更細節的處理。更適用於圖片。

After making this decision, there are a fair bit of formats to choose from: JPEG, GIF, PNG–8, PNG–24, or newest formats such as WEBP or JPEG-XR. With such an abundance of options, how do we ensure we’re picking the right one? Here’s a basic way of finding the best format to go with:

  • JPEG: imagery with many colours (e.g. photos)
  • PNG–8: imagery with a few colours
  • PNG–24: imagery with partial transparency
  • GIF: animated imagery
    決定好以後,咱們能夠選擇幾種格式:JPEG, GIF, PNG–8, PNG–24,或最新格式,如WEBP或JPEG-XR。有了這麼多的選擇,咱們如何確保咱們選擇了合適的格式?這是找到最佳格式的基本方法:
  • JPEG:具備多種顏色的圖像(例如照片)
  • PNG-8:具備幾種顏色的圖像
  • PNG-24:具備部分透明度的圖像
  • GIF: 動圖

Photoshop can optimise each of these on export through various settings such as decreasing quality, reducing noise or number of colours. Ensure that designers are aware of performance practices and can prepare the right type of asset with the right optimisation presets. If you’d like to know more how to develop images, head to Lara Hogan’s invaluable Designing for Performance.
Photoshop能夠經過各類設置,例如下降畫質,下降噪點或減小顏色數量來優化圖片。確保設計師瞭解性能實踐,並可使用正確的優化方式來提供恰當格式的資源。若是您想了解如何優化圖片,請前往Lara Hogan’s invaluable Designing for Performance

嘗試新格式

Experimenting with new formats
There are a few newer players in the spectrum of image formats, namely WebP, JPEG 2000 and JPEG-XR. All of them are developed by browser vendors: WebP by Google, JPEG 2000 by Apple and JPEG-XR by Microsoft.
圖像格式有幾個較新的玩家,即WebP,JPEG 2000和JPEG-XR。全部這些都是由瀏覽器供應商開發的:Google的WebP,Apple的JPEG 2000和Microsoft的JPEG-XR。

WebP is easily the most popular contender, supporting both lossless and lossy compression, which makes it incredibly versatile. Lossless WebP is 26% smaller than PNGs and 25–34% smaller than JPGs. With 74% browser support it can safely be used with fallback, introducing up to 1/3 savings in transferred bytes. JPGs and PNGs can be converted to WebP in Photoshop and other image processing apps as well as through command line interfaces (brew install webp).
WebP是最受歡迎的競爭者,支持無損和失真壓縮,這使得它很是通用。無損WebP比PNG小26%,比JPG小25-34%。有了74%的瀏覽器支持,它能夠安全地用於回退,最多可節省1/3的傳輸字節。JPG和PNG圖片能夠在Photoshop或其餘圖像處理應用程序以及命令行界面(brew install webp)中轉換爲WebP。

If you’d like to explore (minor) visual differences between these formats I recommend this nifty demo on Github.
若是你想探索這些格式之間的視覺差別,我建議看看這個在Github上的demo

用工具和算法進行圖片優化

Optimising with tools and algorithms
Even using incredibly efficient image formats doesn’t warrant skipping post-processing optimisation. This step is crucial.
即便使用高效的圖像格式也不值得跳事後處理優化。這一步很重要。

If you’ve chosen SVGs, which are usually relatively small in size, they too have to be compressed. SVGO is a command line tool that can swiftly optimise SVGs through stripping unnecessary metadata. Alternatively, use SVGOMG by Jake Archibald if you prefer a web interface or are limited by your operating system. Because SVG is an XML-based format, it can also be subject to GZIP compression on the server side.
若是你選擇了一般尺寸相對較小的SVG,那麼也須要被壓縮。SVGO是一個命令行工具,能夠經過剝離沒必要要的元數據來快速優化SVG。或者,若是你喜歡Web界面或受操做系統的限制,請使用Jake ArchibaldSVGOMG。由於SVG是基於XML的格式,它也能夠在服務器端進行GZIP壓縮。

ImageOptim is an excellent choice for most of the other image types. Comprising of pngcrush, pngquant, MozJPEG, Google Zopfli and more, it bundles a bunch of great tools in a comprehensive, Open Source package. Available as a Mac OS app, command line interface and Sketch plugin, ImageOptim can be easily implemented into an existing workflow. For those on Linux or Windows, most of the CLIs ImageOptim relies on can be used on your platform.
ImageOptim是大多數其餘圖像類型的絕佳選擇。包括pngcrush,pngquant,MozJPEG,Google Zopfli等,它在一個開源包中捆綁了一堆很棒的工具。做爲Mac OS應用程序,命令行界面和Sketch插件,ImageOptim能夠輕鬆地應用到現有的工做流程中。對於那些在Linux或Windows上,大多數ImageOptim的CLI也可使用。

If you’re inclined to try emerging encoders, earlier this year, Google released Guetzli — an Open Source algorithm stemming from their learnings with WebP and Zopfli. Guetzli is supposed to produce up to 35% smaller JPEGs than any other available method of compression. The only downside: slow processing times (a minute of CPU per megapixel).
若是你想嘗試新興的編碼器,Google今年早些時候發佈了Guetzli - 源自WebP和Zopfli的開源算法。 Guetzli應該比任何其餘可用的壓縮方法產生比35%更小的JPEG。惟一的缺點:處理時間慢(CPU每百萬像素一分鐘)。

When choosing tools make sure they produce desired results and fit into teams’ workflow. Ideally, automate the process of optimisation, so no imagery slips through the cracks unoptimised.
選擇工具時,請確保它們適合項目和團隊的工做流程。理想狀況下,構建自動化優化,這樣能夠基本覆蓋全部需優化的圖片。

自適應圖像

Responsible and responsive imagery
A decade ago we might have gotten away with one resolution to serve all, but the landscape of ever-changing, responsive web is very different today. That’s why we have to take extra care in implementing visual resources we’ve so carefully optimised and ensuring they cater for the variety of viewports and devices. Fortunately, thanks to Responsive Images Community Group we’re perfectly equipped to do so with picture element and srcset attribute (both have 85%+ support).
十年前,咱們可能已經拋棄了一次性解決全部問題的觀念,現在的不斷髮展的響應式網絡更需如此。這就是爲何咱們在渲染咱們精心優化過的視覺資源時必須特別當心,並確保它們適應各類視口和設備。幸運的是,感謝Responsive Images社區小組,咱們徹底可使用圖片元素和srcset屬性(都有85%+支持)。

srcset屬性

The srcset attribute
Srcset works best in the resolution switching scenario—when we want to display imagery based on users’ screen density and size. Based on a set of predefined rules in srcset and sizes attributes the browser will pick the best image to serve accordingly to the viewport. This technique can bring great bandwidth and request savings, especially for the mobile audience.
Srcset在分辨率切換方案中效果最佳 - 當咱們要根據用戶的屏幕分辨率和大小顯示圖像時。基於srcset和size屬性中的一組預約義規則,瀏覽器將選擇最佳圖像,以便相應地提供給視口。這種技術能夠帶來很大的帶寬,需謹慎使用,特別是針對移動用戶。

An example of srcset usage

圖片元素

The picture element
Picture element and the media attribute are designed to make art direction easy. By providing different sources for varying conditions (tested via media-queries), we’re able always able to keep the most important elements of imagery in the spotlight, no matter the resolution.
圖片元素和媒體屬性旨在使藝術化變得簡單。經過爲不一樣場景提供不一樣資源(經過媒體查詢測試),不管場景怎麼變化,咱們始終能夠展示正確的圖像。

clipboard.png

Make sure to read Jason Grigsby’s Responsive Images 101 guide for a thorough explanation of both approaches.

務必閱讀Jason Grigsby的Responsive Images 101指南,以便完全理解這兩種方法。

圖片放到CDN

Delivery with image CDNs
The last step of our journey to performant visuals is delivery. All assets can benefit from using a content delivery network, but there are specific tools targeting imagery, such as Cloudinary or imgx. The benefit of using those services goes further than reducing traffic on your servers and significantly decreasing response latency.
圖片優化的最後一步是傳輸。全部資源能夠放到CDN上,現有一些特定的工具能夠定位到圖像,例如「Cloudinary」或「imgx」。使用這些服務的好處遠遠超過想辦法減小服務器上的流量,並顯着下降了響應延遲,提高加載速度。

CDNs can take out a lot of complexity from serving responsive, optimised assets on image-heavy sites. The offerings differ (and so does the pricing) but most handle resizing, cropping and determining which format is best to serve to your customers based on devices and browsers. Even more than that — they compress, detect pixel density, watermark, recognise faces and allow post-processing. With these powerful features and ability to append parameters to URLs serving user-centric imagery becomes a breeze.
CDN在圖像重磅的網站上響應和優化資源會加劇複雜度。資源不一樣(花費也是如此),可是大多數處理器能夠根據設備和瀏覽器調整合適的大小,裁剪並肯定最合適的格式。並且 - 它們能夠進行壓縮,檢測像素密度,水印,識別面部並容許後處理。藉助這些強大的功能和將參數附加到以用戶爲中心的圖像的URL的功能變得垂手可得。

Image performance checklist

  1. Choose the right format
  2. Use vector wherever possible
  3. Reduce the quality if change is unnoticeable
  4. Experiment with new formats
  5. Optimise with tools and algorithms
  6. Learn about srcset and picture
  7. Use an image CDN

圖像性能清單

  1. 選擇正確的格式
  2. 儘量使用矢量
  3. 若是變化不明顯,則下降畫質
  4. 嘗試新格式
  5. 用工具和算法進行圖片優化
  6. 瞭解srcset和圖片元素
  7. 圖片放到CDN

優化網頁字體

Optimising web fonts
The ability to use custom fonts is an incredibly powerful design tool. But with power comes a lot of responsibility. With whooping 68% of websites leveraging web fonts this type of asset is one of the biggest performance offenders (easily averaging 100KB, depending on the number of variants and typefaces).
使用自定義字體的是一個很是強大進步。但權力越多責任越大。有68%的網站利用網絡字體,這種類型的資產是最大的性能違規者之一(容易平均100KB,取決於變體和字體的數量)。

Even when weight isn’t the most major issue, Flash of Invisible Text (FOIT) is. FOIT occurs when web fonts are still loading or failed to be fetched, which results in an empty page and thus, inaccessible content. It might be worth it to carefully examine whether we need web fonts in the first place. If so, there are a few strategies to help us mitigate the negative effect on performance.
即便重量不是最大的問題,Flash的隱形文本(FOIT)也是。當網頁字體在加載中或未能被抓取時,會發生FOIT,這會致使空白頁面,從而致使沒法訪問的內容。首先要仔細檢查咱們是否須要網頁字體。若是是這樣,有一些策略能夠幫助咱們減輕對性能方面的負面影響。

選擇正確的格式

Choosing the right format
There are four web font formats: EOT, TTF, WOFF and more recent WOFF2. TTF and WOFF are most widely adopted, boasting over 90% browser support. Depending on the support you’re targeting it’s most likely safe to serve WOFF2 and fall back to WOFF for older browsers. The advantage of using WOFF2 is a set of custom preprocessing and compression algorithms (like Brotli) resulting in approx. 30% file-size reduction and improved parsing capabilities.
有四種網絡字體格式:EOT,TTF,WOFF和近期的WOFF2。 TTF和WOFF被普遍採用,擁有超過90%的瀏覽器支持。根據你的項目,儘量穩定地支持WOFF2,並在舊版瀏覽器上使用WOFF。使用WOFF2的優勢是其有一套定製的預處理和壓縮算法(如Brotli),能縮小大約30%的文件大小和提高解析功能。

When defining the sources of web fonts in @font-face use the format() hint to specify which format should be utilised.
@font-face中定義網頁字體的來源時,請使用format()來指定應使用哪一種格式。

If you’re using Google Fonts or Typekit to serve your fonts, both of these tools have implemented a few strategies to mitigate their performance footprint. Typekit now serves all kits asynchronously, preventing FOIT as well as allows for extended cache period of 10 days for their JavaScript kit code (instead of default 10 minutes). Google Fonts automatically serves the smallest file, based on the capabilities of the users’ device.
若是你使用Google Fonts或Typekit來做爲字體,這兩種字體都實施了一些策略來減輕其性能消耗。 Typekit如今能夠異步地爲全部工具包提供服務,保護FOIT以及容許其JavaScript代碼延長10天的緩存時間(而不是默認10分鐘)。 Google Fonts能夠根據用戶設備的性能自動提供最小的文件。

斟酌字體選擇

Audit font selection
No matter whether self-hosting or not, the number of typefaces, font weights and styles will significantly affect your performance budgets.
不管是否自主託管,字體數量、大小和樣式都將顯著影響你的性能預算。

Ideally, we can get away with one typeface featuring normal and bold stylistic variants. If you’re not sure how to make font selection choices refer to Lara Hogan’s Weighing Aesthetics and Performance.
理想狀況下,咱們能夠避免使用正常或加粗格式上變體的字體。若是不肯定如何選擇字體,請參考Lara Hogan的衡量美與性能

使用Unicode格式的字集

Use Unicode-range subsetting
Unicode-range subsetting allows splitting large fonts into smaller sets. It’s a relatively advanced strategy but might bring significant savings especially when targeting Asian languages (did you know Chinese fonts average at 20,000 glyphs?). The first step is to limit the font to the necessary language set, such as Latin, Greek or Cyrillic. If a web font is required only for logotype usage, it’s worth it to use Unicode-range descriptor to pick specific characters.
Unicode格式的字集容許將大字體分割成較小的集合。這是一個相對先進的方案,特別是針對亞洲語言的時候,可能會帶來顯著的空間節省(你知道中文字體的平均數爲20,000字形嗎?)。第一步是將字體限制爲必要的語言集,例如拉丁語,希臘語或西里爾語。若是使用一個網絡字體只是爲了進行標識,則推薦使用Unicode格式的描述符來指定字符。

The Filament Group released an Open Source command-line utility, glyph hanger that can generate a list of necessary glyphs based on files or URLs. Alternatively, the web-based Font Squirrel Web Font Generator offers advanced subsetting and optimisation options. If using Google Fonts or Typekit choosing a language subset is built into the typeface picker interface, making basic subsetting easier.
Filament團隊發佈了一個開源命令行工具,能夠根據文件或URL生成必需字形列表。或者,基於Web的Font Squirrel和Font Generator提供的高級字集和優化選項。若是在字體選擇器界面中內置了Google Fonts或Typekit,則使用基本字集更容易。

創建一個字體加載策略

Establish a font loading strategy
Fonts are render-blocking — because the browser has to build both the DOM and CSSOM first; web fonts won’t be downloaded before they’re used in a CSS selector that matches an existing node. This behaviour significantly delays text rendering, often causing the Flash of Invisible Text (FOIT) mentioned before. FOIT is even more pronounced on slower networks and mobile devices.
因爲瀏覽器必須首先構建DOM和CSSOM,以後再渲染字體;在解析到應用了web fonts的CSS選擇器以前,不會下載web fonts。這種行爲有明顯的延遲文本現象,特別是前面提到的Flash隱藏文本(FOIT)。在較慢的網絡和移動設備上,FOIT延遲更加明顯。

Implementing a font loading strategy prevents users from not being able to access your content. Often, opting for Flash of Unstyled Text (FOUT) is the easiest and most effective solution.
實施字體加載策略可防止用戶沒法訪問您的內容。一般,選擇Flash的Unstyled Text(FOUT)是最簡單和最有效的解決方案。

font-display is a new CSS property providing a non-JavaScript reliant solution. Unfortunately, it has partial support (Chrome and Opera only) and is currently under development in Firefox and WebKit. Still, it can and should be used in combination with other font loading mechanisms.
font-display是提供非JavaScript依賴解決方案的新CSS屬性。不幸,它僅有部分瀏覽器支持(Chrome和Opera),目前正在Firefox和WebKit中開發。儘管如此,它應該與其餘字體加載機制結合使用。

clipboard.png
font-display property in action

Luckily, Typekit’s Web Font Loader and Bram Stein’s Font Face Observer can help manage font loading behaviour. Additionally, Zach Leatherman, an expert on web font performance, published A Comprehensive Guide to Font Loading Strategies which will aid in choosing the right approach for your project.
幸運的是,Typekit的Web Font Loader和Bram Stein的Font Face Observer能夠幫助管理字體加載行爲。此外,網頁字體性能專家Zach Leatherman發佈了「字體加載策略綜合指南」,這將有助於爲你的項目對web fonts的選擇。

Web font performance checklist

  1. Chose the right format
  2. Audit the font selection
  3. Use Unicode-range subsetting
  4. Establish a font loading strategy

Web字體性能清單

  1. 選擇正確的格式
  2. 斟酌字體選擇
  3. 使用Unicode格式的字集
  4. 創建一個字體加載策略
  5. 使用font-display屬性

優化JavaScript

Optimising JavaScript
At the moment, the average size of JavaScript bundle is 446 KB, which already makes it second biggest type of an asset size-wise (following images).
目前,JavaScript軟件包的平均大小爲446 KB,佔用資源的比例已經達到第二(僅次於圖片)。

What we might not realise is that there’s a much more sinister performance bottleneck hidden behind our beloved JavaScript.
咱們可能沒有意識到,咱們所愛的JavaScript隱藏着更加險惡的性能瓶頸。

監控JavaScript的傳輸

Monitor how much JavaScript is delivered
Optimising delivery is only one step in combating web page bloat. After JavaScript is downloaded, it has to be parsed, compiled and run by the browser. A quick look at a few popular sites and it becomes obvious that gzipped JS becomes at least three times bigger after unpacking. Effectively, we are sending giant blobs of code down the wire.
優化傳輸只是減輕網頁膨脹的一步。JavaScript下載後,必須由瀏覽器進行解析,編譯和運行。當你快速瀏覽一些流行的網站,明顯gzip壓縮的JS在解壓以後至少要增長三倍。實際上,咱們正在發送一大堆代碼。

clipboard.png
Parse times for 1MB of JavaScript on different devices. Image courtesy of Addy Osmani and his JavaScript Start-up Performance article.
在不一樣的設備上屢次解析1MB的JavaScript。圖片由Addy Osmani和他的JavaScript Start-up Performance文章提供。

Analysing parse and compile times becomes crucial to understanding when apps are ready to be interacted with. These timings vary significantly based the hardware capabilities of users’ device. Parse and compile can easily be 2–5x times higher on lower end mobiles. Addy’s research confirms that on an average phone an app will take 16 seconds to reach an interactive state, compared to 8 seconds on a desktop. It’s crucial to analyse these metrics, and fortunately, we can do so through Chrome DevTools.
apps在解析和編譯後是否可用,分析其中的耗時相當重要。所耗時間因用戶設備的硬件功能而異。在低端手機解析和編譯比高端手機上慢2-5倍Addy的研究證明,在通常手機上,一個應用程序將須要16秒才能正常使用,而在桌面上爲8秒。分析這些指標相當重要,幸運的是,咱們能夠經過Chrome DevTools來實現。

clipboard.png
Investigating parse and compile in Chrome Dev Tools
在Chrome開發工具中調查解析和編譯

Make sure to read Addy Osmani’s detailed write-up on JavaScript Start-up Performance.
請務必閱讀Addy Osmani對JavaScript性能優化的詳細說明

去除沒必要要的依賴

Get rid of unnecessary dependencies
The way modern package managers work can easily obscure the number and the size of dependencies. webpack-bundle-analyzer and Bundle Buddy are great, visual tools helping identify code duplication, biggest performance offenders and outdated, unnecessary dependencies.
現代軟件包管理器的工做方式能夠垂手可得地掩蓋依賴包的數量和大小。webpack-bundle-analyzerBundle Buddy是很好的可視化工具,幫助識別重複代碼,最大的性能阻礙和過期的、沒必要要的依賴。

clipboard.png
Webpack bundle analyzer in action.
使用中的Webpack bundle analyzer

We can make imported package cost even more visible with Import Cost extension in VS Code and Atom.
經過導入VS CodeAtom中的擴展,咱們可使包引入成本更加明顯。

clipboard.png
Import Code VS Code extension.
導入代碼VS導入代碼擴展

實現代碼拆分

Implement code splitting
Whenever possible, we should only serve the necessary assets to create the desired user experience. Sending a full bundle.js file to the user, including code handling interactions they might never see is less than optimal (imagine downloading JavaScript handling an entire app when visiting a landing page). Similarly, we shouldn’t be universally serving code targeting specific browsers or user agents.
只要有可能,咱們只需提供必要的資源來實現所需的用戶體驗。向用戶發送一個完整的bundle.js文件,包括他們可能永遠看不到的代碼,處理交互效果是不太理想的(假設在訪問首頁時下載JavaScript處理整個應用程序)。一樣,咱們不該該廣泛投放針對特定瀏覽器或用戶代理的代碼。

Webpack, one of the most popular module bundlers, comes with code splitting support. Most straightforward code splitting can be implemented per page (home.js for a landing page, contact.js for a contact page, etc.), but Webpack offers few advanced strategies like dynamic imports or lazy loading that might be worth looking into as well.
Webpack是最受歡迎的模塊打包工具之一,支持代碼拆分。最明顯的是能夠每頁實現代碼拆分(用於首頁的home.js,聯繫人頁面的contact.js等),而且Webpack提供了幾個的高級策略,例如動態導入和延遲加載,值得一看。

框架選擇的考慮

Consider framework alternatives
JavaScript front-end frameworks are constantly on the rise. According to the State of JavaScript 2016 survey React is the most popular option. Carefully auditing architecture choices though might show that you’d be better off with a much more lightweight alternative such as Preact (note that Preact isn’t trying to be a full React reimplementation, just a highly performant, less featured virtual DOM library). Similarly, we can swap bigger libraries for smaller altrnatives — moment.js for date-fns (or in particular case of moment.js remove unused locales).
JavaScript前端框架不斷增長。根據2016年對JavaScript的調查,React是最受歡迎的選擇。仔細考慮架構選擇,雖然你可能會使用更爲輕量級的替代方案(例如Preact)(請注意,Preact不會是一個完整的React從新實現,只是一個高性能,功能較差的虛擬DOM庫)。相似地,咱們能夠用較小的庫來替代 - 例如用於date-fns的moment.js(或者是刪除moment.js未使用的部分)。

Before starting a new project, it’s worthwhile to determine what kind of features are necessary and pick the most performant framework for your needs and goals. Sometimes that might mean opting for writing more vanilla JavaScript instead.
在開始一個新項目以前,肯定什麼樣的功能是必要的,併爲你的需求和目標選擇最具性能的框架。不過可能意味着選擇寫更多的JavaScript代碼。

JavaScript performance checklist

  1. Monitor how much JavaScript is delivered
  2. Get rid of unnecessary dependencies
  3. Implement code splitting
  4. Consider framework alternatives

JavaScript性能清單

  1. 監控JavaScript的傳輸
  2. 避免沒必要要的依賴
  3. 代碼拆分
  4. 框架選擇的考慮

跟蹤性能優化之路

Tracking performance and the road forward
We’ve talked about several strategies that in most cases will yield positive changes to the user experience of products we’re building. Performance can be a tricky beast though, and it’s necessary to track the long-term results of our tweaks.
咱們已經討論過幾種策略,在大多數狀況下會對咱們正在創建的產品的用戶體驗產生積極的變化。性能多是一個棘手的問題,並且有必要跟蹤咱們調整的長期結果。

以用戶爲中心的性能指標

User-centric performance metrics
Great performance metrics aim to be as close to portraying user experience as possible. Long established onLoad, onContentLoaded or SpeedIndex tell us very little about how soon sites can be interacted with. When focusing only on the delivery of assets, it’s not easy to quantify perceived performance. Fortunately, there are a few timings that paint quite a comprehensive picture of how soon content is both visible and interactive.
優秀的性能指標旨在儘量接近用戶體驗。長期創建onLoad,onContentLoaded或SpeedIndex告訴咱們不多關於網站能夠互動多久的信息。當僅關注資源傳輸時,是不容易肯定性能的。幸運的是,有一些時間點的圖片能夠全面地描述內容的顯示和交互過程。

clipboard.png

Those metrics are First Paint, First Meaningful Paint, Visually Complete and Time to Interactive.
這些指標是第一次繪製,第一次有意義的繪製,視覺完整和互動時間。

  • First Paint: the browser changed from a white screen to the first visual change.
  • First Meaningful Paint: text, images and major items are viewable.
  • Visually Complete: all content in the viewport is visible.
  • Time to Interactive: all content in the viewport is visible and ready to interact with (no major main thread JavaScript activity).
  • 第一次繪製:瀏覽器從白色屏幕到第一次視覺變化。
  • 第一次有意義的繪製:文字,圖像和主要模塊可見。
  • 視覺完整:視窗中的全部內容均可見。
  • 互動時間:視窗中的全部內容都是可見的,能夠隨時進行交互(沒有主要的JavaScript線程活動)。

These timings directly correspond to what the users see therefore make excellent candidates for tracking. If possible, record all, otherwise pick one or two to have a better understanding of perceived performance. It’s worth keeping an eye on other metrics as well, especially the number of bytes (optimised and unpacked) we’re sending.
這些時間點直接對應於用戶看到的優秀性能跟蹤。若是可能,記錄所有,不然選擇一兩個來更好地瞭解感知的表現。值得注意的是其餘指標,特別是咱們發送的字節數(優化和解壓)。

設置性能預算

Setting performance budgets
All of these figures might quickly become confusing and cumbersome to understand. Without actionable goals and targets, it’s easy to lose track of what we’re trying to achieve. A good few years ago Tim Kadlec wrote about the concept of performance budgets.
全部這些數字可能會很快會使理解變得混亂和麻煩。沒有可操做的目標和場景,很容易偏離咱們正在實現的內容。幾年前,Tim Kadlec寫了關於性能預算的概念。

Unfortunately, there’s no magical formula for setting them. Often performance budgets boil down to competitive analysis and product goals, which are unique to each business.
不幸的是,沒有設置它們的神奇公式。性能預算一般歸結爲競爭分析和產品目標,這是每一個業務都不一樣的。

When setting budgets, it’s important to aim for a noticeable difference, which usually equals to at least 20% improvement. Experiment and iterate on your budgets, leveraging Lara Hogan’s Approach New Designs with a Performance Budget as a reference.
設定預算時,重要的是要達到明顯的效果,一般至少改善20%。實踐和迭代您的預算,利用Lara Hogan新設計的方法,做爲性能預算參考。

Try out Performance Budget Calculator or Browser Calories Chrome extension to aid in creating budgets.
試用性能預算計算器或瀏覽器卡路里Chrome擴展程序來幫助創建預算。

持續監測

Continuous monitoring
Monitoring performance shouldn’t be manual. There are quite a few powerful tools offering comprehensive reporting.
監控性能不該該是手動的。有不少強大的工具提供全面的反饋。

Google Lighthouse is an Open Source project auditing performance, accessibility, progressive web apps, and more. It’s possible to use Lighthouse in the command line or as just recently, directly in Chrome Developer Tools.
Google Lighthouse是一個審覈性能,可訪問性,漸進式網絡應用程序等的開源項目。能夠在命令行中或直接在Chrome Developer Tools中使用Lighthouse。

clipboard.png
Lighthouse performing a performance audit.
Lighthouse執行性能審計。

For continuous tracking opt-in for Calibre that offers performance budgets, device emulation, distributed monitoring and many other features that are impossible to get without carefully building your own performance suite.
根據Calibre的連續跟蹤選項,能夠提供性能預算,設備仿真,分佈式監控和許多其餘功能,無需仔細構建本身的性能套件便可得到。

clipboard.png
Comprehensive performance tracking in Calibre.
全面的性能跟蹤。

Wherever you’re tracking, make sure to make the data transparent and accessible to the entire team, or in smaller organisations, the whole business.
不管您在跟蹤什麼地方,請確保使整個團隊或整個企業的小型組織可以透明地訪問數據。

Performance is a shared responsibility, which spans further than developer teams — we’re all accountable for the user experience we’re creating, no matter role or title.
性能是一項共同責任,甚至高於開發團隊,咱們對所建立的用戶體驗負責,不管處於什麼樣的職位和角色。

It’s incredibly important to advocate for speed and establish collaboration processes to catch possible bottlenecks as early as product decisions or design phases.
倡導速度和創建協做流程,在處理產品決策或設計階段早期可能遇到的瓶頸是很是重要的。

創建性能意識

Building performance awareness and empathy
Caring about performance isn’t only a business goal (but if you need to sell it through sales statistics do so with PWA Stats). It’s about fundamental empathy and putting the best interest of the users first.
關心性能不只僅是一個業務目標(可是若是您須要經過銷售統計數據來進行銷售,那麼用PWA統計)。基本的共識和使用者的最大利益是第一位。

As technologists, it’s our responsibility not to hijack attention and time people could be happily spending elsewhere. Our objective is to build tools that are conscious of time and human focus.
做爲技術專家,不要過度控制注意力和時間,人們可能會樂意花費時間在其餘地方。咱們的目標是創建能夠節省時間和人性化的工具。

Advocating for performance awareness should be everyone’s goal. Let’s build a better, more mindful future for all of us with performance and empathy in mind.倡導性能意識應該是每一個人的目標。讓咱們經過性能共識創建一個更好,更有意義的將來。

相關文章
相關標籤/搜索