且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何等待脚本加载

更新时间:2023-12-04 23:51:28

此任务的合适工具是MutationObserver,它监视DOM修改.

The proper tool for this task is MutationObserver that monitors DOM modifications.

由于document_start上的MutationObserver可以减慢页面速度(即使只是一点点),因此我们仅观察到<head>元素,由于其中的元素数量很少,因此速度非常快.

Since MutationObserver at document_start can slow down the page (even if just by a little), we'll only observe the <head> element, which is super-fast due to the small amount of elements there.

// there's no HEAD yet at document-start, let's wait until we have it
new MutationObserver((mutations, observer) => {
  if (document.head) {
    observer.disconnect();
    monitorLinks();
  }
}).observe(document.documentElement, {childList: true});

function monitorLinks() {
  const onMutation = mutations => {
    for (const {addedNodes} of mutations) {
      for (const n of addedNodes) {
        if (n.nodeName === 'LINK' && n.rel === 'preconnect') {
          processLink(n);
        }
      }
    }
  };
  // the HEAD may have some children already
  onMutation([{
    addedNodes: document.getElementsByTagName('link'),
  }]);
  // watch for the newly added children of HEAD
  new MutationObserver(onMutation).observe(document.head, {childList: true});
}

function processLink(link) {
  console.log(link);
}