检查iframe的内容是否完全加载的最好方法是使用load事件,正如@Gaafar建议的那样:
$("#iframe").on("load", function() {
// code to execute after the content has loaded.
}
虽然您自己的answer 提出了一个可行的替代方案,但这并不是最好的选择,因为除非父窗口和iframe 的内容由同一个域提供服务,否则您将因@987654323 而被阻止@。因此,此解决方案对于可能提供外部 iframe 的其他用户没有任何价值。
因此,可以编辑您的代码,直到达到以下最佳形式:
var frm = $("#allin");
frm.submit(function(ev) {
/* Show the loading. */
$("#loading").show();
/* Send an AJAX request. */
$.ajax({
type: frm.attr("method"),
url: frm.attr("action"),
data: frm.serialize(),
success: function(data) {
/* Create the iframe and set its properties. */
var nfr = $("<iframe>", {
"id": "frame",
"class": "grid",
"src": "iframe.php",
});
/* Set the 'load' event. */
nfr.on("load", function () {
/* Fade the loading out. */
$("#loading").fadeOut();
});
/* Empty framewrap and the append the created iframe. */
$("#framewrap").empty().append(nfr);
}
});
/* Prevent the default behaviour. */
ev.preventDefault();
});
为了简单起见,我创建了一个简单的 sn-p 来帮助说明我的观点,使用 timeout 而不是 XMLHttpRequest:
片段:
/* ----- JavaScript ----- */
setTimeout(function () {
/* Create the iframe and set its properties. */
var nfr = $("<iframe>", {
"id": "frame",
"class": "grid",
"src": "https://example.com",
});
/* Set the 'load' event. */
nfr.on("load", function () {
/* Fade the loading out. */
$("#loading").fadeOut();
});
/* Empty framewrap and the append the created iframe. */
$("#framewrap").empty().append(nfr);
}, 1000);
/* ----- CSS ----- */
#loading {
position: absolute;
top: 0;
height: 300px;
width: 500px;
background: black;
}
#frame {
position: absolute;
top: 0;
height: 300px;
width: 500px;
}
<!----- HTML ----->
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id = "framewrap"></div>
<div id = "loading"></div>
正如你在评论中提到的,“已经有一个同名的 iframe...”,一个同名的 iframe 已经存在,这就是为什么 load不适合你。
我不确定你的意思,因为你说iframe 已经存在,但是你在添加到问题的代码中创建它(再次?),但是以下 sn-p 证明即使 iframe 可能在 load 事件侦听器附加之前存在,只需更改 src 属性即可使其工作:
片段:
/* ----- JavaScript ----- */
setTimeout(function () {
/* Cache the iframe. */
var nfr = $("#frame");
/* Res-set the 'src' attribute. */
nfr[0].src = nfr[0].src;
/* Set the 'load' event. */
$("#frame").on("load", function () {
/* Fade the loading out. */
$("#loading").fadeOut();
});
}, 1000);
/* ----- CSS ----- */
#loading {
position: absolute;
top: 0;
height: 300px;
width: 500px;
background: black;
}
#frame {
position: absolute;
top: 0;
height: 300px;
width: 500px;
}
<!----- HTML ----->
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id = "framewrap">
<iframe id = "frame" class = "grid" src = "https://example.com"></iframe>
</div>
<div id = "loading"></div>