UNPKG

quicklink

Version:

Faster subsequent page-loads by prefetching in-viewport links during idle time

2 lines (1 loc) 2.15 kB
function e(e,n,t,r){var o={headers:{accept:"*/*"}};return n||(o.mode="no-cors"),t&&(o.credentials="include"),o.priority=r?"high":"low",window.fetch?fetch(e,o):function(e,n){return new Promise(function(t,r,o){(o=new XMLHttpRequest).open("GET",e,o.withCredentials=n),o.setRequestHeader("Accept","*/*"),o.onload=function(){200===o.status?t():r()},o.send()})}(e,t)}var n,t=(n=document.createElement("link")).relList&&n.relList.supports&&n.relList.supports("prefetch")?function(e,n){return new Promise(function(t,r,o){(o=document.createElement("link")).rel="prefetch",o.href=e,n&&o.setAttribute("crossorigin","anonymous"),o.onload=t,o.onerror=r,document.head.appendChild(o)})}:e,r=window.requestIdleCallback||function(e){var n=Date.now();return setTimeout(function(){e({didTimeout:!1,timeRemaining:function(){return Math.max(0,50-(Date.now()-n))}})},1)},o=new Set;function i(e,n){return Array.isArray(n)?n.some(function(n){return i(e,n)}):(n.test||n).call(n,e.href,e)}function c(e){if(void 0===e&&(e={}),window.IntersectionObserver){var n=function(e){e=e||1;var n=[],t=0;function r(){t<e&&n.length>0&&(n.shift()(),t++)}return[function(e){n.push(e)>1||r()},function(){t--,r()}]}(e.throttle||1/0),t=n[0],c=n[1],a=e.limit||1/0,s=e.origins||[location.hostname],f=e.ignores||[],l=e.timeoutFn||r,h=e.prefetchChunks,d=function(n){u(n,e.priority).then(c).catch(function(n){c(),e.onError&&e.onError(n)})},m=new IntersectionObserver(function(e){e.forEach(function(e){e.isIntersecting&&(m.unobserve(e=e.target),o.size<a&&t(function(){h?h(e,d):d(e.href)}))})});return l(function(){(e.el||document).querySelectorAll("a").forEach(function(e){s.length&&!s.includes(e.hostname)||i(e,f)||m.observe(e)})},{timeout:e.timeout||2e3}),function(){o.clear(),m.disconnect()}}}function u(n,r){var i=navigator.connection;if(i){if(i.saveData)return Promise.reject(new Error("Cannot prefetch, Save-Data is enabled"));if(/2g/.test(i.effectiveType))return Promise.reject(new Error("Cannot prefetch, network conditions are poor"))}return Promise.all([].concat(n).map(function(n){return o.has(n)?[]:(o.add(n),(r?e:t)(new URL(n,location.href).toString()))}))}export{c as listen,u as prefetch};