使用JavaScript和网络信息API进行自适应网络服务
栏目: JavaScript · 发布时间: 7年前
内容简介:根据网络速度进行不同的内容推送,比如网速速度慢就推送分辨率低的图片,这种自适应网络服务是使用专门的API实现。navigator.connection.effectiveType 可用于根据用户网络连接的质量提供不同的内容。effectiveType是Network Information API的一个属性,通过navigator.connection对象向JavaScript公开。在Chrome中,您可以将以下内容放入DevTools以查看有效的连接类型(ECT):console.log(navigat
根据网络速度进行不同的内容推送,比如网速速度慢就推送分辨率低的图片,这种自适应网络服务是使用专门的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>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:- 未知网络服务分析之调试技巧
- Istio网络服务网格 超越Kubernetes技术
- Go36-46-访问网络服务(socket)
- Kafka 服务端 网络层 架构
- linux入门系列11--Centos7网络服务管理
- Netty 4.1.16.Final 发布,Java 网络服务框架
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Inside Larry's and Sergey's Brain
Richard Brandt / Portfolio / 17 Sep 2009 / USD 24.95
You’ve used their products. You’ve heard about their skyrocketing wealth and “don’t be evil” business motto. But how much do you really know about Google’s founders, Larry Page and Sergey Brin? Inside......一起来看看 《Inside Larry's and Sergey's Brain》 这本书的介绍吧!