我有一个奇怪的问题,我想知道这是否是此事件的正常行为。我有一个“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");
}
}
链接到笔