1

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

链接到

4

1 回答 1

1

每个页面只触发一次该事件。您正在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);
});

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

于 2020-07-04T17:01:04.980 回答