javascript - 附加 iframe 时触发 DOMContentLoaded 事件
问题描述
我有一个奇怪的问题,我想知道这是否是此事件的正常行为。我有一个“DOMContentLoaded”事件。当 DOM 准备好时,此事件按预期触发。但是,如果 iframe 附加到 DOM,则“DOMContentLoaded”事件会再次触发。我的问题是,这是预期的反应吗?
// log
var msgEl = document.getElementById("content-msg");
// dom ready
var loadIfDomReady = function (event) {
console.log('DOM fully loaded and parsed');
msgEl.innerHTML += "<br/> DOM fully loaded and parsed";
alert("DOM fully loaded and parsed");
}
window.document.addEventListener('DOMContentLoaded', loadIfDomReady(event), false);
function createIframe() {
var _iframe = document.createElement("iframe");
// shotgun approach
_iframe.style.visibility = "hidden";
_iframe.style.position = "absolute";
_iframe.style.display = "none";
_iframe.style.width = "0";
_iframe.style.height = "0";
return _iframe;
}
// vars
var url = "https://codepen.io/alexandro218/pen/zYrpryK";
function appendIframe() {
msgEl.innerHTML = "<br/>Append button clicked";
if(!refreshIframe) {
var refreshIframe = createIframe();
document.body.appendChild(refreshIframe);
refreshIframe.src = url;
refreshIframe.onload = function (event) {
console.log("iframe is loaded");
msgEl.innerHTML += "<br/>iframe is loaded";
};
msgEl.innerHTML += "<br/>!iframe src appended";
} else {
refreshIframe.src = url;
msgEl.innerHTML += "<br/>iframe src appended";
console.log("iframe src appended");
}
}
链接到笔
解决方案
每个页面只触发一次该事件。您正在alert
父页面中。然后,当您添加同一页面的 iframe 时,您将alert
进入 iframe 页面。
您可以看到不同之处,例如,如果您location.href
在警报中显示当前页面,?i_am_an_iframe
并向 iframe URL 添加类似内容:
https://codepen.io/blex41/pen/abdqdmo
但是您的情况实际上并不需要使用DOMContentLoaded
来重现:
// On page load
console.log('Hello from ' + window.location.href);
btn.addEventListener('click', function() {
var _iframe = document.createElement("iframe");
_iframe.src = "https://codepen.io/blex41/pen/XWXZXNL?i_am_an_frame";
// Add the iframe, which will have the same script running inside it,
// and hence produce another console.log, but with a different location.href
document.body.appendChild(_iframe);
});
推荐阅读
- javascript - javascript/jquery clearInterval 有效但有延迟
- java - 如何从 excel 中获取整数值并存储在 Soap UI 属性步骤中
- python - python SpeechRecognition 模块中的麦克风无法识别语音
- java - REST API POST/PUT/DELETE 方法仅在关闭 CSRF 的情况下在 Postman 中工作(Spring Security)
- android - 提供带有 Hilt 的 Activity 实例
- python - discord.py:如何在嵌入中使用 Spotify 类?
- css - 图像上的边框半径不起作用(Android)
- ios - 使用 Vision 扫描照片库中的图像
- python - 对于具有不同时区的不同位置,我是否应该在 UTC 中存储重复发生的本地事件的日期?
- java - 在 JavaFX 中更新 TableCell 时的奇怪行为