Categories
JavaScript Answers

How to Refresh a Page with JavaScript?

Spread the love

Refreshing a page is an operation that we have to do sometimes.

In this article, we’ll look at how we can refresh a page with JavaScript.

location.reload() with No Argument

The location.reload() method is one method that we can call to refresh a page with JavaScript.

It does the same thing as the reload button in our browsers.

This method can only be called if it’s issued from the same domain as the app itself.

history.go(0)

The history.go method lets us load a specific page from the session history.

We can use it to move forward by passing in a positive number, and move backward if we pass in a negative number.

And if we pass in 0, we can refresh the page.

history.go()

Passing in nothing to history.go is the same as passing in 0.

It’ll also refresh the page.

location.href = location.pathname

We can assign location.pathname , which has the part of the URL after the hostname.

We can assign it to location.href to trigger navigation to the same page, which is the same as refreshing the page.

location.href is the property that we can assign to navigate to the given URL.

location.replace

The location.replace replaces the current resource with the provided URL.

replace doesn’t save a record into session history if we trigger navigation with it.

For instance, we can write:

location.replace(location.pathname)

to reload the page since location.pathname has the URL path to the current page.

location.reload with true

We can call location.reload(true) to refresh a page by fetching a fresh, non-cached copy of the page HTML.

Nothing will be served from the cache.

This is the same as doing a hard refresh in the browser.

location.reload(true) behaves the same as location.reload() for browsers where the argument isn’t accepted like Google Chrome.

Conclusion

There are several ways we can refresh a page with JavaScript.

Leave a Reply

Your email address will not be published. Required fields are marked *