Слушайте сценарии, добавленные в документ - PullRequest
0 голосов
/ 19 марта 2019

Есть ли событие DOM, которое запускается каждый раз, когда скрипт добавляется / загружается?

Я строю расширение, которое должно ждать, пока не станет доступен определенный объект глобального окна, и мне нужно ждать, пока он существует.

Ответы [ 2 ]

2 голосов
/ 19 марта 2019

Вот пример определения, когда тег скрипта был 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 голос
/ 19 марта 2019
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

...