UNPKG

quicklink

Version:

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

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