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