使用 JavaScript 和网络信息 API 的自适应服务
navigator.connection.effectiveType
有助于根据用户网络连接质量提供不同的资产。
effectiveType是Network Information API的一个属性,通过navigator.connection对象向 JavaScript 公开。在 Chrome 中,您可以将以下内容拖放到 DevTools 中以查看有效连接类型 (ECT):
console.log(navigator.connection.effectiveType); // 4G
可能的值为effectiveType
“slow-2g”、“2g”、“3g”或“4g”。在网速较慢的情况下,此功能允许您通过提供较低质量的资源版本来提高页面加载速度。
在 Chrome 62 之前,我们仅向开发人员公开理论上的网络连接类型(通过navigator.connection.type
),而不是客户端实际体验到的网络质量。
Chrome 的有效连接类型的实现现在是通过最近观察到的往返时间 (rtt) 和下行链路值的组合来确定的。
它将测量的网络性能总结为最相似的蜂窝连接类型(例如 2G),即使实际连接是 WiFi。例如,假设您使用的是星巴克 WiFi,但您的实际有效网络类型是 2G 或 3G。
那么如何响应网络质量的变化呢?我们可以使用connection.onchange
事件监听器来监控连接变化:
function onConnectionChange() {
const { rtt, downlink, effectiveType, saveData } = navigator.connection;
console.log(`Effective network connection type: ${effectiveType}`);
console.log(`Downlink Speed/bandwidth estimate: ${downlink}Mb/s`);
console.log(`Round-trip time estimate: ${rtt}ms`);
console.log(`Data-saver mode on/requested: ${saveData}`);
}
navigator.connection.addEventListener('change', onConnectionChange)
下面是一个快速测试,我在 DevTools 中模拟了“低端移动”配置文件,并能够从“4g”切换到“2g”条件:
effectiveType
Android 版 Chrome、Opera 和 Firefox 均支持此功能。此外,还有许多其他网络质量提示navigator.connection
,包括rtt
和。downlink
downlinkMax
我曾经用过一个开源项目,effectiveType
叫做 Vue.js的 Google Doodles应用。通过数据绑定,我们可以根据 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 Worker 配对以适应用户离线的情况。
对于调试,您可以使用 Chrome 标志“force-effective-connection-type”覆盖网络质量估计值(该标志可从 chrome://flags 设置)。DevTools 网络模拟也可以为 ECT 提供有限的调试体验。
effectiveType
值也通过客户端提示公开,允许开发人员将 Chrome 的网络连接速度传达给服务器。
有关此功能的更多阅读,请参阅:
- Google Chrome 网络信息 API 示例
- 连接感知组件
- 使用 NetInfo API 和服务工作者的动态资源
- 基于网络的图像加载
- Chrome 62 Beta:网络质量评估器 API
- 发货意向:用于网络质量的 NetInfo API 扩展
你也可以在addyosmani.com上找到这篇文章
文章来源:https://dev.to/addyosmani/adaptive-serving-using-javascript-and-the-network-information-api-331p