DOMContentLoaded 事件在附加 iframe 时触发

DOMContentLoaded event triggers when iframe attached

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

link 到 pen

每个页面只会触发一次该事件。您正在 alert 访问父页面。然后,当您添加同一页面的 iframe 时,您正在 alerting 在 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