Mils
Mils

Reputation: 388

How to reload the page one time using javaScript

I want to reload my page after all my code is loaded without using a button.

I used: location.reload();

The problem is that it repeatedly reloads my page all time.

Upvotes: 0

Views: 4644

Answers (3)

Grinn
Grinn

Reputation: 5543

Your window.reload() is getting hit every time the page is reloaded. Do something like this:

if(window.location.href.indexOf('?reloaded') === -1) window.location.href = window.location.href + "?reloaded=true";

This assumes that the page isn't using any other url parameters.

EDIT

As Matt Ball pointed out, using localStorage or cookies won't be restrictive to a single tab or window, but as Jackson Sandland pointed out in the comments, my above-given solution will alter the browser history. After doing some digging I came up with another, admittedly "hacky" but seemingly effective solution: Using window.name instead of a flag in the URL:

if(window.name !== "refreshed") {
    window.name = "refreshed";
    window.location.refresh();
}

If you'd like to test this out, paste the following in an HTML file and load it in your browser:

<script>
window.name = prompt("Window name", window.name);
</script>

Enter a new name, then refresh the page. You'll see that on refresh the new name is displayed. Similarly, if you then open a second tab with the same file, you can set the name for that tab independently of the other.

Upvotes: 7

Pablo
Pablo

Reputation: 1093

Your best bet is to flag somewhere that it has been reloaded once. Using cookies or localStorage as said by Matt, if you need per-tab you can change the location.hash

Maybe you can help us understand WHY you want to reload, there could be another way.

Upvotes: 3

Matt Ball
Matt Ball

Reputation: 359986

You need to store some sort of state outside of the page's JavaScript that will indicate whether or not to refresh. One way is to use localStorage, or a cookie, but neither of these will work per-tab or per-window.

Upvotes: 2

Related Questions