MCPcopy
hub / github.com/ampproject/amphtml / preconnectPolyfill_

Method preconnectPolyfill_

src/preconnect.js:282–317  ·  view source on GitHub ↗

* Safari does not support preconnecting, but due to its significant * performance benefits we implement this crude polyfill. * * We make an image connection to a "well-known" file on the origin adding * a random query string to bust the cache (no caching because we do want to * actual

(ampdoc, origin)

Source from the content-addressed store, hash-verified

280 * @private
281 */
282 preconnectPolyfill_(ampdoc, origin) {
283 // Unfortunately there is no reliable way to feature detect whether
284 // preconnect is supported, so we do this only in Safari, which is
285 // the most important browser without support for it.
286 if (
287 this.features_.preconnect ||
288 !(this.platform_.isSafari() || this.platform_.isIos())
289 ) {
290 return;
291 }
292
293 // Don't attempt to preconnect for ACTIVE_CONNECTION_TIMEOUT_MS since
294 // we effectively create an active connection.
295 // TODO(@cramforce): Confirm actual http2 timeout in Safari.
296 const now = Date.now();
297 this.origins_[origin] = now + ACTIVE_CONNECTION_TIMEOUT_MS;
298 // Make the URL change whenever we want to make a new request,
299 // but make it stay stable in between. While a given page
300 // would not actually make a new request, another page might
301 // and with this it has the same URL. If (and that is a big if)
302 // the server responds with a cacheable response, this reduces
303 // requests we make. More importantly, though, it reduces URL
304 // entropy as seen by servers and thus allows reverse proxies
305 // (read CDNs) to respond more efficiently.
306 const cacheBust = now - (now % ACTIVE_CONNECTION_TIMEOUT_MS);
307 const url =
308 origin +
309 '/robots.txt?_AMP_safari_preconnect_polyfill_cachebust=' +
310 cacheBust;
311 const xhr = new XMLHttpRequest();
312 xhr.open('HEAD', url, true);
313 // We only support credentialed preconnect for now.
314 xhr.withCredentials = true;
315
316 xhr.send();
317 }
318}
319
320/**

Callers 1

url_Method · 0.95

Calls 5

isSafariMethod · 0.80
isIosMethod · 0.80
nowMethod · 0.80
openMethod · 0.45
sendMethod · 0.45

Tested by

no test coverage detected