国产xxxx99真实实拍_久久不雅视频_高清韩国a级特黄毛片_嗯老师别我我受不了了小说

資訊專欄INFORMATION COLUMN

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

young.li / 2965人閱讀

摘要:從現狀談及性能優化原文出處性能優化指南如今網絡發展迅猛,這對我們構建的互聯網平臺要求也更高。這就說明,我們在開發時,并沒有站在用戶的角度上換位思考,更別談性能優化。因此,我們可通過區分關鍵資源并調整加載的優先級來實現性能優化。

從web現狀談及性能優化

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

性能優化指南
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.
如今網絡發展迅猛,這對我們構建的互聯網平臺要求也更高。而我們卻疲于反思用戶與我們之間的聯系。這就說明,我們在開發時,并沒有站在用戶的角度上換位思考,更別談性能優化。

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

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...)。

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?
作為技術人員,我們擁有絕對的優勢。用最新、高配置的電腦和手機,網速也超快,這讓我們很容易認為普羅大眾也是這樣(事實上,是很少很少)。
構建網絡平臺時,如果我們安于開發特權、缺乏用戶同理心,將會導致極糟的用戶體驗。
那么,在設計和開發時,怎樣才能做到性能優化呢?

優化所有資源

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、統計代碼、廣告...)。因此,我們可通過區分關鍵資源并調整加載的優先級來實現性能優化。

With 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"屬性,手動設置該資源優先加載,來確保所期望的內容及時呈現。這種技術可以顯著改善“交互時間”,使最佳用戶體驗成為可能。

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中的預加載,預取和優先級》。

General performance checklist

Cache aggressively

Enable compression

Prioritise critical assets

Use content delivery networks

普遍的性能優化方式

積極地使用緩存

使用壓縮

優先加載關鍵性請求

使用內容傳送網絡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 Archibald的SVGOMG。因為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屬性中的一組預定義規則,瀏覽器將選擇最佳圖像,以便相應地提供給視口。這種技術可以帶來很大的帶寬,需謹慎使用,特別是針對移動用戶。

圖片元素

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.
圖片元素和媒體屬性旨在使藝術化變得簡單。通過為不同場景提供不同資源(通過媒體查詢測試),無論場景怎么變化,我們始終可以展現正確的圖像。

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

Choose the right format

Use vector wherever possible

Reduce the quality if change is unnoticeable

Experiment with new formats

Optimise with tools and algorithms

Learn about srcset and picture

Use an image CDN

圖像性能清單

選擇正確的格式

盡可能使用矢量

如果變化不明顯,則降低畫質

嘗試新格式

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

了解srcset和圖片元素

圖片放到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中開發。盡管如此,它應該與其他字體加載機制結合使用。


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

Chose the right format

Audit the font selection

Use Unicode-range subsetting

Establish a font loading strategy

Web字體性能清單

選擇正確的格式

斟酌字體選擇

使用Unicode格式的字集

建立一個字體加載策略

使用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在解壓之后至少要增加三倍。實際上,我們正在發送一大堆代碼。


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來實現。


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-analyzer和Bundle Buddy是很好的可視化工具,幫助識別重復代碼,最大的性能阻礙和過時的、不必要的依賴。


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 Code和Atom中的擴展,我們可以使包引入成本更加明顯。


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

Monitor how much JavaScript is delivered

Get rid of unnecessary dependencies

Implement code splitting

Consider framework alternatives

JavaScript性能清單

監控JavaScript的傳輸

避免不必要的依賴

代碼拆分

框架選擇的考慮

跟蹤性能優化之路

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告訴我們很少關于網站可以互動多久的信息。當僅關注資源傳輸時,是不容易確定性能的。幸運的是,有一些時間點的圖片可以全面地描述內容的顯示和交互過程。

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。


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的連續跟蹤選項,可以提供性能預算,設備仿真,分布式監控和許多其他功能,無需仔細構建自己的性能套件即可獲得。


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.
倡導性能意識應該是每個人的目標。讓我們通過性能共識建立一個更好,更有意義的未來。

文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。

轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/51465.html

相關文章

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

    摘要:從現狀談及性能優化原文出處性能優化指南如今網絡發展迅猛,這對我們構建的互聯網平臺要求也更高。這就說明,我們在開發時,并沒有站在用戶的角度上換位思考,更別談性能優化。因此,我們可通過區分關鍵資源并調整加載的優先級來實現性能優化。 從web現狀談及性能優化 原文出處:《Karolina Szczur: The State of the Web》 性能優化指南The Internet is ...

    paney129 評論0 收藏0
  • web現狀談及前端性能優化

    摘要:從現狀談及性能優化原文出處性能優化指南如今網絡發展迅猛,這對我們構建的互聯網平臺要求也更高。這就說明,我們在開發時,并沒有站在用戶的角度上換位思考,更別談性能優化。因此,我們可通過區分關鍵資源并調整加載的優先級來實現性能優化。 從web現狀談及性能優化 原文出處:《Karolina Szczur: The State of the Web》 性能優化指南The Internet is ...

    mzlogin 評論0 收藏0
  • 前端每周清單第 41 期 : Node 與 Rust、OpenCV 的火花,網絡安全二三事

    摘要:的網站仍然使用有漏洞庫上周發布了開源社區安全現狀報告,發現隨著開源社區的日漸活躍,開源代碼中包含的安全漏洞以及影響的范圍也在不斷擴大。與應用安全是流行的服務端框架,本文即是介紹如何使用以及其他的框架來增強應用的安全性。 showImg(https://segmentfault.com/img/remote/1460000012181337?w=1240&h=826); 前端每周清單專注...

    syoya 評論0 收藏0
  • 前端每周清單第 29 期:Web 現狀分析與優化策略、Vue 單元測試、Headless Chrom

    摘要:前端每周清單第期現狀分析與優化策略單元測試爬蟲作者王下邀月熊編輯徐川前端每周清單專注前端領域內容,以對外文資料的搜集為主,幫助開發者了解一周前端熱點分為新聞熱點開發教程工程實踐深度閱讀開源項目巔峰人生等欄目。 showImg(https://segmentfault.com/img/remote/1460000011008022); 前端每周清單第 29 期:Web 現狀分析與優化策略...

    HackerShell 評論0 收藏0
  • 王下邀月熊_Chevalier的前端每周清單系列文章索引

    摘要:感謝王下邀月熊分享的前端每周清單,為方便大家閱讀,特整理一份索引。王下邀月熊大大也于年月日整理了自己的前端每周清單系列,并以年月為單位進行分類,具體內容看這里前端每周清單年度總結與盤點。 感謝 王下邀月熊_Chevalier 分享的前端每周清單,為方便大家閱讀,特整理一份索引。 王下邀月熊大大也于 2018 年 3 月 31 日整理了自己的前端每周清單系列,并以年/月為單位進行分類,具...

    2501207950 評論0 收藏0

發表評論

0條評論

young.li

|高級講師

TA的文章

閱讀更多
最新活動
閱讀需要支付1元查看
<