← 中文资源

简体中文版本

navigator.connection 按网络质量降载

Chromium 的 navigator.connection 提供 effectiveType、saveData、rtt;先做特性检测,saveData 优先尊重用户省流意愿,再按 2g/3g/4g 选择低码率或完整媒体。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

NetworkInformation unavailable — ship the full assets

实现说明

顶层就这几处状态:connection。

使用要点

  • 这是浏览器侧代码——navigator 在 Node 里解析不到。

常见问题

安装包是准备工作的一部分吗?

不需要。只用内建 API,安装这一步可以省掉。 文件的状态由几个模块级绑定持有:connection。

核心语句

const light = connection.effectiveType === '2g' || connection.effectiveType === 'slow-2g';
const connection = navigator.connection;

代码示例

// Network Information API: Chromium exposes effectiveType, saveData, rtt
// and downlink; feature-detect because other engines omit it.
const connection = navigator.connection;

if (!connection) {
  console.log('NetworkInformation unavailable — ship the full assets');
} else {
  // saveData means the user asked for Data Saver: respect it before
  // anything else, regardless of measured quality.
  if (connection.saveData) {
    console.log('saveData on — serve text-only variant');
  } else {
    const light = connection.effectiveType === '2g' || connection.effectiveType === 'slow-2g';
    console.log(`effectiveType ${connection.effectiveType}, rtt ${connection.rtt}ms -> ${light ? 'poster + low bitrate' : 'full media'}`);
  }
}