每30秒更改一次iframe源。

问题描述:

我在我的网页上加载了一个iframe。 30秒后,我想更改iframe的来源以加载其他网站。这很好用jQuery(setTimeout函数),但我的问题是性能。当我更改源代码时,需要15秒将页面加载到iframe中。直到内容被加载后,我一直留在黑屏。一旦页面加载后是否可以更改源代码?有什么我可以在jQuery内预加载网页吗?每30秒更改一次iframe源。

+0

来自不同域的iframe中的内容? – epascarello

如果您使用ajax调用检索内容,则可以在新内容到达时将旧内容替换为新内容,并且页面不会显示为空白。根据你在做什么,你可以看看jQuery .load()函数,或者只是使用ajax调用并自己插入内容。

当然,您必须拥有适当的同源特权才能修改iframe的内部结构。

您可以在页面上的同一位置放置两个iframe,但其中一个预加载内容,然后在30秒后将它们交换。然后,您更改以前可见的网址,开始将网址加载到该网址中 - 然后重复。

您可以编写一个脚本,以检测当页面(在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秒的“超时”,如果页面花太多长时间加载。