main/Prefetch.js

import { prefetch, listen } from 'quicklink';
import saveData from '../utils/saveData';

/**
 * Prefetch article links to improve page transitions.
 * We're using a tool called quicklink: https://github.com/GoogleChromeLabs/quicklink.
 * The tool automatically loads urls in the background during browser idle time.
 * It works cross-browser but won't run on slow network speeds or when save data is set.
 *
 * @module Prefetch
 */
const Prefetch = {
	selectors: {
		container: '.l-content__inner',
	},

	init() {
		if ( false === saveData() ) {
			// prefetch home url, otherwise skip nav
			if ( window.location.href !== 'https://globalnews.ca/' ) {
				prefetch( 'https://globalnews.ca/' );
			}

			listen({
				el: document.querySelector( this.selectors.container ),
				origins: this.origins,
				delay: 600,
				throttle: 5,
				limit: 50,
				hrefFn: ( element ) => {
					// skip urls that have already have a hash value
					if ( element.hash.length > 0 ) {
						return '';
					}

					// add a hash value to url so comscore skips tracking these links
					// this value is used by pwaworker.js to flag prefetched links
					// pwaworker.js then ensures a Purpose: prefetch header is added to the request
					// this flags to servers that it's a prefetch request and not a navigation request
					return `${element.href}#gnca-prefetch`;
				},
			});
		}
	},
};

export default Prefetch;