DOMContentLoaded 事件在 iframe 附加时触发



我有一个奇怪的问题,我想知道这是否是这个事件的正常行为。我有一个"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,并向 iframe URL 添加类似?i_am_an_iframe的内容,则可以看到差异:

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);
});

https://codepen.io/blex41/pen/XWXZXNL

相关内容

  • 没有找到相关文章