收听添加到文档的脚本

问题描述 投票:0回答:2

是否每次添加/加载脚本时都会触发DOM事件?

我正在构建一个必须等​​到某个全局窗口对象可用的扩展,我需要等待它存在。

javascript html firefox-webextensions
2个回答
2
投票

以下是检测脚本标记何时为1:添加到页面,2:已加载的示例。 (我在NodeList上的循环可能需要一些工作。)

检测脚本标记

//Wait for the initial DOM...
document.addEventListener('DOMContentLoaded', function() {
    console.log("First page load...");

    //Create the observer
    let myObserver = new MutationObserver(function(mutationList, observer) {
        mutationList.forEach((mutation) => {
            switch(mutation.type) {
                case 'childList' :
                    if(mutation.addedNodes && mutation.addedNodes.length) {
                        let nodes = mutation.addedNodes;
                        for(var i=0; i < nodes.length; i++) {
                            if(nodes[i].nodeName.toLowerCase() === 'script') {
                                console.log("Script tag added");
                            }
                        }
                    }
                    break;
            }
        });
    });

    //Observe the body and head as that's where scripts might be placed
    let body = document.querySelector("body");
    let head = document.querySelector("head");

    //options to look for per-element
    //childList and subtree must be set to true
    let options = {
        childList:true,
        subtree:true
    };
    myObserver.observe(body, options);
    myObserver.observe(head, options);
});

setTimeout(function() {
    let script = document.createElement("script");
    script.setAttribute("integrity", "sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=");
    script.setAttribute("crossorigin", "anonymous");
    script.setAttribute("src", "http://code.jquery.com/jquery-3.3.1.min.js");
    script.onload = function() {
        console.log("Script loaded!");
    };
    document.querySelector("head").appendChild(script);
}, 1000);

1
投票
var targetNode = document;
var observerOptions = {
  childList: true,
  attributes: true,
  subtree: true //Omit or set to false to observe only changes to the parent node.
}

function callback(mutationList, observer) {
  mutationList.forEach((mutation) => {
    if(mutation.type=='childList'){
      var addedNodes=mutation.addedNodes
      for(x=0;x<addedNodes.length;x++){
        if(addedNodes[x].tagName == 'script'){
          //Do what you will
        }
      }
    }
  });
}

var observer = new MutationObserver(callback);
observer.observe(targetNode, observerOptions);

像这样的东西? (未经测试)修改自:https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver/MutationObserver

© www.soinside.com 2019 - 2024. All rights reserved.