如何等待脚本加载 [英] How to wait for scripts to be loaded

查看:171
本文介绍了如何等待脚本加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个Chrome扩展程序,并且在我的contentScript中,我有一个循环所有<link>元素并检查其是否具有rel="preconnect"属性的函数.如果为true,则扩展名的图标将更改.

I am building a Chrome extension and in my contentScript, I have a function which loops all the <link> elements and check whether it has rel="preconnect" attribute. If true, the icon of the extension will change.

contentScript在文档开始处运行并运行该功能.该函数运行onDomLoaded.当prerender直接在HTML代码中时,该扩展程序可以正常工作.但是,当JS生成prerender时,图标不会更改.可能是因为在发生onDomLoaded时脚本未完全加载.

The contentScript runs at document start and the function. The function runs onDomLoaded. When the prerender is directly in HTML code, the extension works perfectly. However when prerender is generated by JS, the icon wont change. Probably because the script is not fully loaded when onDomLoaded happens.

但是,当我改用window.onload时,它确实很慢并且图标会延迟更改,因为它等待脚本完全加载.如何处理这种情况并仅在需要时等待?

However when I use window.onload instead, it is really slow and the icon changes with a delay because it wait for the scripts to be fully loaded. How to deal with that situation and wait only if needed?

清单

content_scripts":
    [{
     "matches": ["https://*/*"],
     "run_at": "document_start",
     "js": ["js/contentScript.js"]
   }]

ContentScript

document.addEventListener("DOMContentLoaded", function(event) {
       //here I loop the page and if preconnect found, change the icon

    )};

推荐答案

此任务的合适工具是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);
}

这篇关于如何等待脚本加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆