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.
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.
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.
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.