preload-links.js
5.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
class RocketPreloadLinks {
constructor( browser, config ) {
this.browser = browser;
this.config = config;
this.options = this.browser.options;
this.prefetched = new Set;
this.eventTime = null;
this.threshold = 1111;
this.numOnHover = 0;
}
/**
* Initializes the handler.
*/
init() {
if (
! this.browser.supportsLinkPrefetch()
||
this.browser.isDataSaverModeOn()
||
this.browser.isSlowConnection()
) {
return;
}
this.regex = {
excludeUris: RegExp( this.config.excludeUris, 'i' ),
images: RegExp( '.(' + this.config.imageExt + ')$', 'i' ),
fileExt: RegExp( '.(' + this.config.fileExt + ')$', 'i' )
};
this._initListeners( this );
}
/**
* Initializes the event listeners.
*
* @private
*
* @param self instance of this object, used for binding "this" to the listeners.
*/
_initListeners( self ) {
// Setting onHoverDelay to -1 disables the "on-hover" feature.
if ( this.config.onHoverDelay > -1 ) {
document.addEventListener( 'mouseover', self.listener.bind( self ), self.listenerOptions );
}
document.addEventListener( 'mousedown', self.listener.bind( self ), self.listenerOptions );
document.addEventListener( 'touchstart', self.listener.bind( self ), self.listenerOptions );
}
/**
* Event listener. Processes when near or on a valid <a> hyperlink.
*
* @param Event event Event instance.
*/
listener( event ) {
const linkElem = event.target.closest( 'a' );
const url = this._prepareUrl( linkElem );
if ( null === url ) {
return;
}
switch ( event.type ) {
case 'mousedown':
case 'touchstart':
this._addPrefetchLink( url );
break;
case 'mouseover':
this._earlyPrefetch( linkElem, url, 'mouseout' );
}
}
/**
*
* @private
*
* @param Element|null linkElem
* @param object url
* @param string resetEvent
*/
_earlyPrefetch( linkElem, url, resetEvent ) {
const doPrefetch = () => {
falseTrigger = null;
// Start the rate throttle: 1 sec timeout.
if ( 0 === this.numOnHover ) {
setTimeout( () => this.numOnHover = 0, 1000 );
}
// Bail out when exceeding the rate throttle.
else if ( this.numOnHover > this.config.rateThrottle ) {
return;
}
this.numOnHover++;
this._addPrefetchLink( url );
};
// Delay to avoid false triggers for hover/touch/tap.
let falseTrigger = setTimeout( doPrefetch, this.config.onHoverDelay );
// On reset event, reset the false trigger timer.
const reset = () => {
linkElem.removeEventListener( resetEvent, reset, { passive: true } );
if ( null === falseTrigger ) {
return;
}
clearTimeout( falseTrigger );
falseTrigger = null;
};
linkElem.addEventListener( resetEvent, reset, { passive: true } );
}
/**
* Adds a <link rel="prefetch" href="<url>"> for the given URL.
*
* @param string url The Given URL to prefetch.
*/
_addPrefetchLink( url ) {
this.prefetched.add( url.href );
return new Promise( ( resolve, reject ) => {
const elem = document.createElement( 'link' );
elem.rel = 'prefetch';
elem.href = url.href;
elem.onload = resolve;
elem.onerror = reject;
document.head.appendChild( elem );
} ).catch(() => {
// ignore and continue.
});
}
/**
* Prepares the target link's URL.
*
* @private
*
* @param Element|null linkElem Instance of the link element.
* @returns {null|*}
*/
_prepareUrl( linkElem ) {
if (
null === linkElem
||
typeof linkElem !== 'object'
||
! 'href' in linkElem
||
// Link prefetching only works on http/https protocol.
[ 'http:', 'https:' ].indexOf( linkElem.protocol ) === -1
) {
return null;
}
const origin = linkElem.href.substring( 0, this.config.siteUrl.length );
const pathname = this._getPathname( linkElem.href, origin );
const url = {
original: linkElem.href,
protocol: linkElem.protocol,
origin: origin,
pathname: pathname,
href: origin + pathname
};
return this._isLinkOk( url ) ? url : null;
}
/**
* Gets the URL's pathname. Note: ensures the pathname matches the permalink structure.
*
* @private
*
* @param object url Instance of the URL.
* @param string origin The target link href's origin.
* @returns {string}
*/
_getPathname( url, origin ) {
let pathname = origin
? url.substring( this.config.siteUrl.length )
: url;
if ( ! pathname.startsWith( '/' ) ) {
pathname = '/' + pathname;
}
if ( this._shouldAddTrailingSlash( pathname ) ) {
return pathname + '/';
}
return pathname;
}
_shouldAddTrailingSlash( pathname ) {
return (
this.config.usesTrailingSlash
&&
! pathname.endsWith( '/' )
&&
! this.regex.fileExt.test( pathname )
);
}
/**
* Checks if the given link element is okay to process.
*
* @private
*
* @param object url URL parts object.
*
* @returns {boolean}
*/
_isLinkOk( url ) {
if ( null === url || typeof url !== 'object' ) {
return false;
}
return (
! this.prefetched.has( url.href )
&&
url.origin === this.config.siteUrl // is an internal document.
&&
url.href.indexOf( '?' ) === -1 // not a query string.
&&
url.href.indexOf( '#' ) === -1 // not an anchor.
&&
! this.regex.excludeUris.test( url.href ) // not excluded.
&&
! this.regex.images.test( url.href ) // not an image.
);
}
/**
* Named static constructor to encapsulate how to create the object.
*/
static run() {
// Bail out if the configuration not passed from the server.
if ( typeof RocketPreloadLinksConfig === 'undefined' ) {
return;
}
const browser = new RocketBrowserCompatibilityChecker( {
capture: true,
passive: true
} );
const instance = new RocketPreloadLinks( browser, RocketPreloadLinksConfig );
instance.init();
}
}
RocketPreloadLinks.run();