javascript - 收听添加到文档中的脚本

标签 javascript html firefox-addon-webextensions

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

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

最佳答案

下面是检测脚本标记何时 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);

关于javascript - 收听添加到文档中的脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55248537/

相关文章:

javascript - 如果使用 javascript 提交表单,则发布错误的值

javascript - 在 Javascript 中完全迭代/抓取 HTML 文档

html - 相对定位的 HTML 元素与父元素重叠

html - 在 bootstrap3 中正确安装表格

javascript - WebExtensions 中的 browser.alarms.create 与 setTimeout/setInterval 有何区别?

javascript - 如何在 Web 扩展弹出窗口中使用 Vue.js?

javascript - 无法在 D3 条形图中的 x 轴上换行中文文本

javascript - Node js/js : Text not appended in file in sequence

javascript - 当文本框清晰时如何禁用按钮?

javascript - 测试方法的存在