quicklink是一个js库,能够预加载出如今视口的网页连接,提升用户体验。它的加载过程以下:
1.检测网页中的连接是否出如今视口中,等待连接出如今视口,执行步骤2。
2.等待浏览器空闲后执行3。
3.判断当前的网络链接是不是2G,若是是则中止执行,若是不是2G网络,执行步骤4。
4.预加载连接指向资源。git
参考连接https://github.com/GoogleChro...github
quicklink的入口函数接受传入的配置参数,经过Object.assign函数和默认的配置选项合并。接着执行timeoutFn异步方法,该方法接收一个回调函数,在回调中主要逻辑以下:
若是传入的options参数中有urls属性,则直接执行预加载,不然经过document.querySelectorAll方法获取全部a标签元素的NodeList,而后便利该元素节点列表,并监视该元素节点ajax
observer.observe(link);
而后判断该a元素对象的href属性值所属的域名是否被容许访问,若是被容许访问,继续判断该连接是否应该被忽略,判断逻辑以下:数组
if (!allowed.length || allowed.includes(link.hostname)) { // If there are any filters, the link must not match any of them isIgnored(link, ignores) || toPrefetch.add(link.href); }
若是连接没有被忽略,则将该节点的href属性值加入到toPrefetch中浏览器
const toPrefetch = new Set(); toPrefetch.add(link.href);
总的代码逻辑以下网络
export default function (options) { options = Object.assign({ timeout: 2e3, priority: false, timeoutFn: requestIdleCallback, el: document, }, options); observer.priority = options.priority; const allowed = options.origins || [location.hostname]; const ignores = options.ignores || []; options.timeoutFn(() => { // If URLs are given, prefetch them. if (options.urls) { options.urls.forEach(prefetcher); } else { // If not, find all links and use IntersectionObserver. Array.from(options.el.querySelectorAll('a'), link => { observer.observe(link); // If the anchor matches a permitted origin // ~> A `[]` or `true` means everything is allowed if (!allowed.length || allowed.includes(link.hostname)) { // If there are any filters, the link must not match any of them isIgnored(link, ignores) || toPrefetch.add(link.href); } }); } }, {timeout: options.timeout}); }
上面经过observer.observe(link)监视节点元素,其中observer是IntersectionObserver对象的实例,被监听的节点对象出如今视口时,会执行new操做时传入的回调函数,并将出如今视口的节点对象经过数组的形式传给该回调。而后在回调中便利传入的数组,若是数组中的元素包含在toPrefetch对象中,则取消对该元素的监视,并对该a标签元素所对应的资源进行预加载。app
const observer = new IntersectionObserver(entries => { entries.forEach(entry => { if (entry.isIntersecting) { const link = entry.target; if (toPrefetch.has(link.href)) { observer.unobserve(link); prefetcher(link.href); } } }); });
若是浏览器支持requestIdleCallback,则使用原生的函数,若是不支持,则使用setTimeout函数作ployfill。异步
const requestIdleCallback = requestIdleCallback || function (cb) { const start = Date.now(); return setTimeout(function () { cb({ didTimeout: false, timeRemaining: function () { return Math.max(0, 50 - (Date.now() - start)); }, }); }, 1); }; export default requestIdleCallback;
预加载策略主要有三种ide
1.<link> prefetch函数
function linkPrefetchStrategy(url) { return new Promise((resolve, reject) => { const link = document.createElement(`link`); link.rel = `prefetch`; link.href = url; link.onload = resolve; link.onerror = reject; document.head.appendChild(link); }); };
2.ajax加载
function xhrPrefetchStrategy(url) { return new Promise((resolve, reject) => { const req = new XMLHttpRequest(); req.open(`GET`, url, req.withCredentials=true); req.onload = () => { (req.status === 200) ? resolve() : reject(); }; req.send(); }); }
3.Fetch请求加载
function highPriFetchStrategy(url) { // TODO: Investigate using preload for high-priority // fetches. May have to sniff file-extension to provide // valid 'as' values. In the future, we may be able to // use Priority Hints here. // // As of 2018, fetch() is high-priority in Chrome // and medium-priority in Safari. return self.fetch == null ? xhrPrefetchStrategy(url) : fetch(url, {credentials: `include`}); }
if (conn = navigator.connection) { // Don't prefetch if the user is on 2G. or if Save-Data is enabled.. if ((conn.effectiveType || '').includes('2g') || conn.saveData) return; }
将上面三种预加载方法封装成函数,暴露给外部使用
const supportedPrefetchStrategy = support('prefetch') ? linkPrefetchStrategy : xhrPrefetchStrategy; function prefetcher(url, isPriority, conn) { if (preFetched[url]) { return; } if (conn = navigator.connection) { // Don't prefetch if the user is on 2G. or if Save-Data is enabled.. if ((conn.effectiveType || '').includes('2g') || conn.saveData) return; } // Wanna do something on catch()? return (isPriority ? highPriFetchStrategy : supportedPrefetchStrategy)(url).then(() => { preFetched[url] = true; }); }; export default prefetcher;