quicklink剖析

简介

quicklink是一个js库,能够预加载出现在视口的网页链接,进步用户体验。它的加载历程以下:
1.检测网页中的链接是不是出现在视口中,守候链接出现在视口,实行步骤2。
2.守候浏览器余暇后实行3。
3.推断当前的收集连接是不是是2G,假如是则住手实行,假如不是2G收集,实行步骤4。
4.预加载链接指向资本。

运用体式格局

参考链接https://github.com/GoogleChro…

quicklink源码剖析

quicklink的进口函数吸收传入的设置参数,经由过程Object.assign函数和默许的设置选项兼并。接着实行timeoutFn异步要领,该要领吸收一个回调函数,在回调中重要逻辑以下:
假如传入的options参数中有urls属性,则直接实行预加载,不然经由过程document.querySelectorAll要领猎取一切a标签元素的NodeList,然后方便该元素节点列表,并看管该元素节点

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});
}

检测link出现在视口

上面经由过程observer.observe(link)看管节点元素,个中observer是IntersectionObserver对象的实例,被监听的节点对象出现在视口时,会实行new操纵时传入的回调函数,并将出现在视口的节点对象经由过程数组的情势传给该回调。然后在回调中方便传入的数组,假如数组中的元素包含在toPrefetch对象中,则作废对该元素的看管,并对该a标签元素所对应的资本举行预加载。

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;

资本要求函数完成

预加载战略重要有三种

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;
    原文作者:treeandgrass
    原文地址: https://segmentfault.com/a/1190000017784796
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞