Holtorf
Holtorf

Reputation: 1491

Force (or ask nicely) to refresh the browser

So I run a site that uses a lot of javascript and ajax. I understand how to make users refresh their browser when the browser loads. But what happens if I need them to refresh their browser after they have loaded the site?

I want to change the ajax that is served to the client to speed up things up, but this is going to cause errors for the users who have not yet refreshed their browser.

The only solution I can come up with is that when a new version of the JavaScript file is required, the site uses a popup that asks the users to force refresh their browsers. (This won't really fix the current version, but would prevent future issues.)

I hate to use a popup for something that I could do automatically. Is there a better way to force updates for the client?

Upvotes: 1

Views: 232

Answers (2)

Joseph Myers
Joseph Myers

Reputation: 6552

You sound like you are having trouble with your JavaScript getting an updated version of the data it loads through Ajax methods, is that correct? For instance, if two Ajax calls try to load 'data.txt', then the second call merely uses the cached version.

You also may be having trouble with loading new versions your script itself.

The way around both of these problems is to add a randomly-generated query string to your script source and your Ajax source.

For example, make one script that loads your main script, like this:

/* loader1.js */
document.write('<script src="mainjavascript.js?.rand=', Math.random(), '"></script>');

And in your HTML, just do

<script src="loader1.js"></script>

The same method works for JavaScript Ajax requests as well. Assuming that "client" is a new XMLHttpRequest() object, and has been properly set up with a readystatechange function and so on, then the you simply append the same query string, like this:

request = client.open('GET', 'data.txt?.rand=' + Math.random(), true);
request.send();

You may be using a library to do your Ajax requests, and so it's even easier then. Just specify the data URL as 'data.txt?.rand=' + Math.random() instead of merely 'data.txt'

Upvotes: 1

Oswald
Oswald

Reputation: 31647

window.location.href = "http://example.com"

replaces the current page with the one pointed to by http://example.com.

Upvotes: 1

Related Questions