Skip prefetching on 2G connections, or when data saver is enabled
This commit is contained in:
parent
d7d271570f
commit
94d6102cc5
3 changed files with 29 additions and 1 deletions
15
packages/labs/prefetch/@types/network-information.d.ts
vendored
Normal file
15
packages/labs/prefetch/@types/network-information.d.ts
vendored
Normal 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;
|
||||
};
|
||||
}
|
|
@ -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 =
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"extends": "../../../tsconfig.base.json",
|
||||
"include": ["src"],
|
||||
"include": ["src", "@types"],
|
||||
"compilerOptions": {
|
||||
"allowJs": true,
|
||||
"module": "ES2020",
|
||||
|
|
Loading…
Reference in a new issue