javascript - 收听添加到文档的脚本
问题描述
每次添加/加载脚本时是否会触发 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);
推荐阅读
- java - 通过 HTMLUnit 使用 Java 进行身份验证时遇到问题。调试问题
- python-2.7 - 发送 SES 模板电子邮件返回“模板数据在尝试传递 TemplateData 中的值时无效
- amazon-web-services - 请求的 URL 返回错误:403,AWS Server less: Amplify app to CodeCommit
- c++ - 我在使用 boost:asio 时是否偏执?
- javascript - 未捕获的类型错误:无法读取属性“getContext”
- javascript - 猫头鹰轮播不会加载图像和按钮
- javascript - 数组类型变量在 setState 上更改为字符串
- android - 为 Roboelectric 将 Android Studio 升级到 Java 1.9 时出现问题
- javascript - 在 JavaScript 函数中执行 php
- php - 如果文件夹中不存在文件,则删除文件夹 - Google Drive API