- 原文地址:Adaptive Serving using JavaScript and the Network Information API
- 原文做者:Addy Osmani
- 譯文出自:掘金翻譯計劃
- 本文永久連接:github.com/xitu/gold-m…
- 譯者:Raoul1996
- 校對者:Guangping、CoderMing
navigator.connection.effectiveType
能夠根據用戶的網絡鏈接質量得出不一樣的結果javascript
effectiveType 是 Network Information API 的一個屬性,在 JavaScript 中經過 navigator.connection 對象在調用。在 Chrome 瀏覽器中,你能夠把如下內容放入 DevTools 中來查看有效的鏈接類型(ECT):前端
console.log(navigator.connection.effectiveType); // 4G
複製代碼
effectiveType
可取值有 'slow-2g'、'2g'、'3g' 或者 '4g'。在網速慢的時候,此功能可讓你經過提供較低質量的資源來提升頁面的加載速度。java
在 Chrome 62 以前,咱們只向開發者公佈了理論上的網絡鏈接類型(經過 navigator.connection.type
)而不是客戶端實際的網絡鏈接質量。android
Chrome 的有效鏈接類型目前是使用最近觀察到的往返時間(rtt)和下行鏈路值的組合來肯定。ios
它將測量到的網絡鏈接性能總結爲最接近的蜂窩網絡鏈接類型(好比 2G),即便你實際鏈接的的 WiFi。如圖所示,你鏈接了星巴克的WiFi,可是實際上你的有效網絡類型是 2G 或者 3G。git
如何應對網絡鏈接質量的變化呢?咱們能夠經過 connection.onchange
事件監聽器來監聽網絡變化:github
function onConnectionChange() {
const { rtt, downlink, effectiveType, saveData } = navigator.connection;
console.log(`有效網絡鏈接類型: ${effectiveType}`);
console.log(`估算的下行速度/帶寬: ${downlink}Mb/s`);
console.log(`估算的往返時間: ${rtt}ms`);
console.log(`打開/請求數據保護模式: ${saveData}`);
}
navigator.connection.addEventListener('change', onConnectionChange)
複製代碼
下面是一個快速測試,我在 DevTools 中模擬了一個 「低網速的手機」 的配置,而且可以從 「4g」 切換到 」2g「:web
effectiveType
在安卓上的 Chrome、Opera 和 Firefox 獲得了支持,有些其它的網絡質量提示能夠在 navigator.connection
中查看,包括 rtt
,downlink
和 downlinkMax
。chrome
我在基於 Vue.js 的開源項目 —— Google Doodles 應用中使用過 effectiveType。基於 ECT 值,咱們能夠經過使用數據綁定就可以把 connection
屬性設置爲 fast
或者 slow
。大體以下:後端
if (/\slow-2g|2g|3g/.test(navigator.connection.effectiveType)) {
this.connection = "slow";
} else {
this.connection = "fast";
}
複製代碼
這可讓咱們去根據用戶的有效鏈接類型呈現不一樣的輸出(視頻或者低分辨率圖片)。
<template>
<div id="home">
<div v-if="connection === 'fast'">
<!-- 1.3MB video -->
<video class="theatre" autoplay muted playsinline control>
<source src="/static/img/doodle-theatre.webm" type="video/webm">
<source src="/static/img/doodle-theatre.mp4" type="video/mp4">
</video>
</div>
<!-- 28KB image -->
<div v-if="connection === 'slow'">
<img class="theatre" src="/static/img/doodle-theatre-poster.jpg">
</div>
</div>
</template>
複製代碼
Max Böck 寫了一篇關於使用 React 網絡感知組件的文章,蠻有意思。他提出瞭如何根據網絡速度渲染不一樣的組件:
switch(connectionType) {
case '4g':
return <Video src={videoSrc} />
case '3g':
return <Image src={imageSrc.hires} alt={alt} />
default:
return <Image src={imageSrc.lowres} alt={alt} />
}
複製代碼
注意:你能夠將 effectiveType
和 Service Workers 搭配使用來應對因爲慢速鏈接而離線了的用戶。
調試的話,你可使用 Chrome flag "force-effective-connection-type" 來覆寫網絡質量估算,這個 flag 能夠在 chrome://flags 中設置。DevTools 網絡模擬也能夠也能夠爲 ETC 提供有限的調試體驗。
effectiveType
值也一樣能夠經過客戶端提示公開,容許開發者將 Chrome 的網絡鏈接速度傳達給服務器。
若是發現譯文存在錯誤或其餘須要改進的地方,歡迎到 掘金翻譯計劃 對譯文進行修改並 PR,也可得到相應獎勵積分。文章開頭的 本文永久連接 即爲本文在 GitHub 上的 MarkDown 連接。
掘金翻譯計劃 是一個翻譯優質互聯網技術文章的社區,文章來源爲 掘金 上的英文分享文章。內容覆蓋 Android、iOS、前端、後端、區塊鏈、產品、設計、人工智能等領域,想要查看更多優質譯文請持續關注 掘金翻譯計劃、官方微博、知乎專欄。