使用JavaScript和网络信息API进行自适应网络服务

根据网络速度进行不同的内容推送,比如网速速度慢就推送分辨率低的图片,这种自适应网络服务是使用专门的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'。在慢速连接上,此功能允许您通过提供较低质量的资源来提高页面加载速度。

如何应对网络质量的变化?我们可以使用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)

effectiveType在Android上的Chrome,Opera和Firefox支持。其他的一些网络质量提示可在navigator.connection包括rtt,downlink和downlinkMax。

在Vue.js中,使用数据绑定,我们能够将connection属性设置为fast或者slow基于ECT值。大致是:


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 type=
"video/webm">
<source type=
"video/mp4">
</video>
</div>
<!-- 28KB image -->
<div v-if=
"connection === 'slow'">
<img class=
"theatre" >
</div>
</div>
</div>
</template>

Adaptive Serving using JavaScript and the Network