我在谷歌上搜索了这个问题,并尝试了许多片段;但一无所获。如何防止iframe
运行两次加载事件?
PAGE.HTML:在 http://maindomain.com 运行
<div class="regionBody">
<iframe frameborder="0" allowtransparency="true" src="http://externaldomain.com/iframepage" height="215" style="border:none;width:100%;"></iframe>
</div>
<script>
$('.regionBody iframe').css({height: someCalculatedHeight});
</script>
IFRAMEPAGE.HTML:运行在 http://externaldomain.com
<div>some elements...</div>
<script src="frame-script.js"/>
帧脚本.js:
var requestsTimeout = null;
function doRequests(callback) {
clearTimeout(requestsTimeout);
$.ajax({
cache: false,
url: some-url,
dataType: 'json',
type: 'GET'
}).done(function (data) {
// putting the result in frame's body
}).complete(function () {
clearTimeout(requestsTimeout);
callback();
});
}
function startRequests() {
requestsTimeout = setTimeout(function () {
console.log('Doing requests...');
doRequests(startRequests);
}, 5000);
}
$(window).load(function () {
console.log('IFrame loaded...');
$(window).resize(function () {
clearTimeout(requestsTimeout);
});
$(this).resize(function () {
clearTimeout(requestsTimeout);
});
$('body').resize(function () {
clearTimeout(requestsTimeout);
});
startRequests();
});
如您所见,我已经尝试了任何可能的方法来防止两次运行 ajax 请求。但我仍然可以在控制台中看到哪些 ajax 调用并行进行两次。我的意思是我同时收到重复的Doing requests...
消息,等等。有什么建议吗?提前谢谢。
如果您只想执行一次请求,则可以使用全局标志 var 来防止多次加载而不是超时:
var has_requested = false; //The global flag
function doRequests(callback) {
//Quit if there's a request in progress
if(has_requested)
return;
has_requested = true;
$.ajax({
cache: false,
url: some-url,
dataType: 'json',
type: 'GET'
}).done(function (data) {
// putting the result in frame's body
}).complete(function () {
callback();
});
}
$(window).load(function () {
//Don't forget to pass your callback here, I let it blank
doRequests();
});
如果你只是想避免并行请求,你可以在.done()
和.complete()
中将标志重置为 false,这样它才会在第一个请求实现时才请求。
编辑
如果要随着时间的推移重复此操作,请使用setInterval
:
$(window).load(function () {
//You'd better store the interval identifier to clear it afterwhile,
//if you think you'll need to.
setInterval(doRequests,5000);
});