Refresh (reload) a page once using jQuery?

Pete picture Pete · Apr 1, 2010 · Viewed 405.8k times · Source

I'm wondering how to refresh/reload a page (or even specific div) once(!) using jQuery?

Ideally in a way right after the DOM structure is available (cf. onload event) and not negatively affecting back button or bookmark functionality.

Please, note: replace() is not allowed due to third-party restrictions.

Answer

Ben picture Ben · Apr 1, 2010

Alright, I think I got what you're asking for. Try this

if(window.top==window) {
    // You're not in a frame, so you reload the site.
    window.setTimeout('location.reload()', 3000); //Reloads after three seconds
}
else {
    //You're inside a frame, so you stop reloading.
}

If it is once, then just do

$('#div-id').triggerevent(function(){
    $('#div-id').html(newContent);
});

If it is periodically

function updateDiv(){
    //Get new content through Ajax
    ...
    $('#div-id').html(newContent);
}

setInterval(updateDiv, 5000); // That's five seconds

So, every five seconds the div #div-id content will refresh. Better than refreshing the whole page.