quicklink
Version:
Faster subsequent page-loads by prefetching in-viewport links during idle time
2 lines (1 loc) • 5.46 kB
JavaScript
;function e(e,r){(null==r||r>e.length)&&(r=e.length);for(var n=0,t=Array(r);n<r;n++)t[n]=e[n];return t}function r(r,n){var t="undefined"!=typeof Symbol&&r[Symbol.iterator]||r["@@iterator"];if(t)return(t=t.call(r)).next.bind(t);if(Array.isArray(r)||(t=function(r,n){if(r){if("string"==typeof r)return e(r,n);var t={}.toString.call(r).slice(8,-1);return"Object"===t&&r.constructor&&(t=r.constructor.name),"Map"===t||"Set"===t?Array.from(r):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?e(r,n):void 0}}(r))||n){t&&(r=t);var o=0;return function(){return o>=r.length?{done:!0}:{done:!1,value:r[o++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function n(e,r,n,t){var o={headers:{accept:"*/*"}};return r||(o.mode="no-cors"),n&&(o.credentials="include"),o.priority=t?"high":"low",window.fetch?fetch(e,o):function(e,r){return new Promise(function(n,t,o){(o=new XMLHttpRequest).open("GET",e,o.withCredentials=r),o.setRequestHeader("Accept","*/*"),o.onload=function(){200===o.status?n():t()},o.send()})}(e,n)}var t,o=(t=document.createElement("link")).relList&&t.relList.supports&&t.relList.supports("prefetch")?function(e,r){return new Promise(function(n,t,o){(o=document.createElement("link")).rel="prefetch",o.href=e,r&&o.setAttribute("crossorigin","anonymous"),o.onload=n,o.onerror=t,document.head.append(o)})}:n,i=window.requestIdleCallback||function(e){var r=Date.now();return setTimeout(function(){e({didTimeout:!1,timeRemaining:function(){return Math.max(0,50-(Date.now()-r))}})},1)},a=new Set,c=new Set,s=!1;function u(e,r){return Array.isArray(r)?r.some(function(r){return u(e,r)}):(r.test||r).call(r,e.href,e)}function l(e){return!e||(e.saveData?new Error("Save-Data is enabled"):!/2g/.test(e.effectiveType)||new Error("network conditions are poor"))}function f(e,t,i,u,f){var d=l(navigator.connection);return d instanceof Error?Promise.reject(new Error("Cannot prefetch, "+d.message)):(c.size>0&&!s&&console.warn("[Warning] You are using both prefetching and prerendering on the same document"),Promise.all([e].flat().map(function(e){return a.has(e)?[]:(a.add(e),function(e,n,t){for(var o=arguments.length,i=new Array(o>3?o-3:0),a=3;a<o;a++)i[a-3]=arguments[a];if(!t)return e.apply(void 0,[n].concat(i));for(var c,s=document.querySelectorAll('a[href="'+n+'"]'),u=new Map,l=function(){var r=c.value,t=function(){var a=setTimeout(function(){return r.removeEventListener("mouseenter",t),r.removeEventListener("mouseleave",o),e.apply(void 0,[n].concat(i))},200);u.set(r,a)},o=function(){var e=u.get(r);e&&(clearTimeout(e),u.delete(r))};r.addEventListener("mouseenter",t),r.addEventListener("mouseleave",o)},f=r(s);!(c=f()).done;)l()}(t?n:o,new URL(e,location.href).toString(),f,i,u,t))})))}function d(e,n){void 0===n&&(n="immediate"),e=[e].flat();var t=l(navigator.connection);if(t instanceof Error)return Promise.reject(new Error("Cannot prerender, "+t.message));if(!HTMLScriptElement.supports("speculationrules"))return f(e,!0,!1,!1,"moderate"===n||"conservative"===n),Promise.reject(new Error("This browser does not support the speculation rules API. Falling back to prefetch."));for(var o,i=r(e);!(o=i()).done;){var u=o.value;c.add(u)}a.size>0&&!s&&console.warn("[Warning] You are using both prefetching and prerendering on the same document");var d=function(e,n){var t=new Map;try{for(var o,i=r(e);!(o=i()).done;){var a=o.value,c=document.createElement("script");c.type="speculationrules",c.text=JSON.stringify({prerender:[{source:"list",urls:[a],eagerness:n}]}),document.head.append(c),t.set(a,c)}}catch(e){return e}return t}(e,n);return d.size>0?Promise.resolve(d):Promise.reject(d)}exports.listen=function(e){if(void 0===e&&(e={}),!window.IntersectionObserver||!("isIntersecting"in IntersectionObserverEntry.prototype))return function(){};var n=function(e){e=e||1;var r=[],n=0;function t(){n<e&&r.length>0&&(r.shift()(),n++)}return[function(e){r.push(e)>1||t()},function(){n--,t()}]}(e.throttle||1/0),t=n[0],o=n[1],l=e.limit||1/0,h=e.threshold||0,v=e.origins||[location.hostname],m=e.ignores||[],p=e.delay||0,g=new Map,w=new Map,y=e.timeoutFn||i,E="function"==typeof e.hrefFn&&e.hrefFn,b=e.prerender||!1;s=e.prerenderAndPrefetch||!1;var A=new IntersectionObserver(function(n){for(var i,u=function(){var n=i.value,u=g.get(n.target.href)||new Set;g.set(n.target.href,u),n.isIntersecting?(n=n.target,u.add(n),function(e,r){r?setTimeout(e,r):e()}(function(){u&&u.size&&(b||s||A.unobserve(n),(s||b)&&c.size<l&&!w.has(n.href)?d(E?E(n):n.href,e.eagerness).then(function(e){for(var n,t=r(e);!(n=t()).done;){var o=n.value,i=o[0],a=o[1];w.set(i,a)}}).catch(function(r){if(!e.onError)throw r;e.onError(r)}):a.size<l&&!b&&t(function(){f(E?E(n):n.href,e.priority,e.checkAccessControlAllowOrigin,e.checkAccessControlAllowCredentials,e.onlyOnMouseover).then(o).catch(function(r){o(),e.onError&&e.onError(r)})}))},p)):(n=n.target,u.delete(n),w.has(n.href)&&w.set(function(e,r){var n=e.get(r);try{n.remove(),e.delete(r)}catch(e){return e}return e}(w,n.href)))},h=r(n);!(i=h()).done;)u()},{threshold:h});return y(function(){for(var n,t=r(e.el&&e.el.length>0&&"A"===e.el[0].nodeName?e.el:(e.el||document).querySelectorAll("a"));!(n=t()).done;){var o=n.value;v.length&&!v.includes(o.hostname)||u(o,m)||A.observe(o)}},{timeout:e.timeout||2e3}),function(){a.clear(),A.disconnect()}},exports.prefetch=f,exports.prerender=d;