javascript - 每 30 秒更改一次 iframe 源。

标签 javascript jquery iframe

我的网页上加载了一个 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/

相关文章:

php - 如何在 Laravel 中将服务器时间转换为本地时间?

javascript - 动态加载和播放 HTML5 视频

javascript - 错误 : admin is not defined using HTTP request with Cloud Functions for Firebase

javascript - 除以 anchor 字符串值?

javascript - 如何从 Javascript 提示框获取值并将其传递到 PHP 变量以便能够保存在 SQL 中?

javascript - 使用 Iframe 作为父窗口

javascript - Chrome : On pressing Enter on a Textbox of a <form> Submits page without calling onClick of submit button on that form

javascript - 如何在 JS 中替换子字符串的所有实例但仅替换整个世界?

php - 有什么办法可以更改 url 是 iframe 吗?

internet-explorer - 如何防止 iframe 页面被插入到 IE 浏览历史记录中