Avery
Avery

Reputation: 89

Reload page without disrupting currently running Javascript

Is there any way to reload a page without resetting Javascript code that is currently running on the page (for example, being run via the Chrome dev console)?

My situation is that I have a page that I need to keep reloading and running code on automatically. However, whenever I refresh the page using window.location.reload( ) it stops any Javascript that I'm currently running on the page.

Is there any way that I can keep refreshing the page but keep running the same code?

Upvotes: 3

Views: 2505

Answers (3)

Avery
Avery

Reputation: 89

Thanks to dandavis for this answer.

By using ajax, I was able to select a div that encompassed the page and selectively reload it. Effectively, this means that the contect of the page was refreshed.

The code looks something like this:

$('#mydiv').load(document.URL +  ' #mydiv');

Example (where middle is the ID of the div):

$('#middle').load(document.URL +  ' #middle');

Upvotes: 1

Vikrant
Vikrant

Reputation: 5036

Without AJAX, I might decide to refresh the entire page every 30 seconds, but with AJAX, I can just make a lightweight request to get the tiny bit of information I need.

Using AJAX to submit forms isn't always the best bet. Asides from not really giving you a clear advantage over posting the form normally, you break conventions such as browser history (although some browsers now include JavaScript "states" as pages in the history).

Example :

        $.ajax({
        url: form_url, 
        type: form_method,      
        data: form_data,     
        cache: false,
        success: function(returnhtml){                          
            $("#result").html(returnhtml); 
            $("#loadingimg").hide();                    
        }
        error: function (xhr, error) {
            alert(error);
        }
    });

WORKING DEMO

Upvotes: 0

Aaron Gillion
Aaron Gillion

Reputation: 2265

It would be better if you could dynamically update your page... but if it isn't possible...

You can host your entire page need refreshing inside a frameset, and do your important JS outside your frameset inside the framepage. Example

Upvotes: 0

Related Questions