实现说明
顶层就这几处状态: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'}`);
}
}