我的网页上加载了一个 iframe。 30 秒后,我想更改 iframe 的源以加载另一个站点。使用 jQuery(setTimeout 函数)效果很好,但我的问题是性能。当我更改源时,将页面加载到 iframe 需要 15 秒。在加载内容之前,我一直停留在空白屏幕上。是否可以仅在页面加载后更改源?我可以在 jQuery 中做些什么来预加载网页吗?
最佳答案
您可以编写这样的脚本,以检测页面(在 iframe 中)何时完成加载:
// Insert iframe in the page
var $iframe = $('<iframe src="http://www.msn.com/"></iframe>').css({
width: '1px',
height: '1px'
}).attr('frameborder', '0').appendTo('body').data('loaded', 'no');
// Function to execute when the page (in the iframe) has finished to load,
// or when the timeout is over
function iframeIsReady() {
if ($iframe.data('loaded') == 'no') {
$iframe.data('loaded', 'yes').css({
width: '800px',
height: '800px'
});
alert('iframe is ready');
}
}
// Detect when the page (in the iframe) has finished to load
$iframe.load(function ($iframe) {
iframeIsReady();
});
// Add an optional timeout
setTimeout(function () {
iframeIsReady();
}, 15000);
如果页面加载时间过长,我还添加了 15 秒的“超时”。
关于javascript - 每 30 秒更改一次 iframe 源。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7341541/