Skip prefetching on 2G connections, or when data saver is enabled

This commit is contained in:
Tony Sullivan 2022-06-27 12:32:11 -05:00
parent d7d271570f
commit 94d6102cc5
3 changed files with 29 additions and 1 deletions

View file

@ -0,0 +1,15 @@
export { };
declare global {
interface NetworkInformation {
// http://wicg.github.io/netinfo/#effectiveconnectiontype-enum
readonly effectiveType: '2g' | '3g' | '4g' | 'slow-2g';
// http://wicg.github.io/netinfo/#savedata-attribute
readonly saveData?: boolean;
}
var NetworkInformation: {
prototype: NetworkInformation;
new(): NetworkInformation;
};
}

View file

@ -1,3 +1,4 @@
/// <reference path="../@types/network-information.d.ts" />
import throttles from 'throttles';
import requestIdleCallback from './requestIdleCallback.js';
@ -72,6 +73,18 @@ export interface PrefetchOptions {
}
export default function prefetch({ selector = 'a[href][rel~="prefetch"]', throttle = 1 }: PrefetchOptions) {
const conn = navigator.connection;
if (typeof conn !== 'undefined') {
// Don't prefetch if using 2G or if Save-Data is enabled.
if (conn.saveData) {
return Promise.reject(new Error('Cannot prefetch, Save-Data is enabled'));
}
if (/2g/.test(conn.effectiveType)) {
return Promise.reject(new Error('Cannot prefetch, network conditions are poor'));
}
}
const [toAdd, isDone] = throttles(throttle);
observer =

View file

@ -1,6 +1,6 @@
{
"extends": "../../../tsconfig.base.json",
"include": ["src"],
"include": ["src", "@types"],
"compilerOptions": {
"allowJs": true,
"module": "ES2020",