quicklink
Version:
Faster subsequent page-loads by prefetching in-viewport links during idle time
2 lines (1 loc) • 2.03 kB
JavaScript
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.appendChild(o)})}:e;var n;const r=window.requestIdleCallback||function(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 c(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||1/0),c=e.limit||1/0,a=e.origins||[location.hostname],u=e.ignores||[],l=e.timeoutFn||r,{prefetchChunks:f}=e,h=t=>{s(t,e.priority).then(n).catch(t=>{n(),e.onError&&e.onError(t)})},d=new IntersectionObserver(e=>{e.forEach(e=>{e.isIntersecting&&(d.unobserve(e=e.target),o.size<c&&t(()=>{f?f(e,h):h(e.href)}))})});return l(()=>{(e.el||document).querySelectorAll("a").forEach(e=>{a.length&&!a.includes(e.hostname)||i(e,u)||d.observe(e)})},{timeout:e.timeout||2e3}),function(){o.clear(),d.disconnect()}}function s(n,r){const{connection:i}=navigator;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(n=>o.has(n)?[]:(o.add(n),(r?e:t)(new URL(n,location.href).toString()))))}export{c as listen,s as prefetch};