2011-09-07 85 views
2

我在我的網頁上加載了一個iframe。 30秒後,我想更改iframe的來源以加載其他網站。這很好用jQuery(setTimeout函數),但我的問題是性能。當我更改源代碼時,需要15秒將頁面加載到iframe中。直到內容被加載後,我一直留在黑屏。一旦頁面加載後是否可以更改源代碼?有什麼我可以在jQuery內預加載網頁嗎?每30秒更改一次iframe源。

+0

來自不同域的iframe中的內容? – epascarello

回答

0

如果您使用ajax調用檢索內容,則可以在新內容到達時將舊內容替換爲新內容,並且頁面不會顯示爲空白。根據你在做什麼,你可以看看jQuery .load()函數,或者只是使用ajax調用並自己插入內容。

當然,您必須擁有適當的同源特權才能修改iframe的內部結構。

0

您可以在頁面上的同一位置放置兩個iframe,但其中一個預加載內容,然後在30秒後將它們交換。然後,您更改以前可見的網址,開始將網址加載到該網址中 - 然後重複。

1

您可以編寫一個腳本,以檢測當頁面(在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秒的「超時」,如果頁面花太多長時間加載。