简体   繁体   中英

Change iframe source every 30 seconds.

I have an iframe loaded on my webpage. After a 30 seconds I want to change the source of the iframe to load another site. This works great using jQuery (setTimeout function) but my issue is performance. It takes 15 seconds to load the page into the iframe when I change the source. I'm stuck with a blank screen until the content is loaded. Is it possible to only change the source once the page has loaded? Is there something I can do within jQuery to preload the webpage?

You can write a script like this, to detect when the page (in the iframe) has finished to load :

// 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);

I added also a "timeout" of 15 seconds, if the page take too long time to load.

If you use an ajax call to retrieve the content, you can replace the old content with the new content when the new content arrives and the page will not show blank. Depending upon what you're doing, you could look at the jQuery .load() function or just use an ajax call and insert the content yourself.

You will, of course, have to have appropriate same-origin privileges in order to modify the internals of the iframe.

You could have two iframes, in the same place on the page, but one with visibility: hidden , which you pre-load the contents into, then after your 30 seconds, swap them over. Then you change the URL on the formerly visibly one to start it loading the new URL into it - and repeat.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM