Hit enter after type your search item

How to refresh a page by jQuery/JavaScript? location.reload, pathname….

Refreshing a webpage by jQuery or JavaScript

A webpage can be refreshed by using different ways by using jQuery or JavaScript.

For example, you may use location.reload method to refresh a page from the browser cache or server side. See the section below for live demos of using location.reload and other ways.

An example of jQuery refresh from browser cache

The location.reload method takes a parameter which is a Boolean. If set as true, the page will be forced to refresh from the server. The default value is false that may refresh the page from the browser cache.

As you click the button in the demo page, it will reload the page by using location.reload default value:

jquery refresh

See online demo and code

The code to refresh the webpage:


A demo of loading from the server side

In this example, the true value is passed to the location.reload as using jQuery. Again, click the button to reload the webpage from the server:

jquery refresh server

See online demo and code

The jQuery code:


Refreshing the page by JavaScript

If you are not the fan of jQuery or not using jQuery in your web project, then you may do the same by using JavaScript. See the following example for refreshing the webpage by using the window.location.reload attribute which is placed in JavaScript code. The code is invoked as you click the button:

javascript refresh

See online demo and code

The JavaScript and markup for reloading the webpage:


The Markup:


Note: you may also use the location.reload rather than window.location.reload to refresh the page.

Automatically refreshing the webpage without clicking the button

In all above examples, the page is refreshed as you clicked the button. In certain scenarios, you may need to refresh the webpage after a certain interval. For that, you may use the setTimeout where you may specify when to execute the function containing refresh code. In that way, the page will be refreshed automatically after specified interval.

For the demo, I have set the interval as five seconds, have a look:

javascript refresh auto

See online demo and code

The code:


What if a page to be refreshed is loaded by post method?

If the current page that is intended to reload by using a button or automatically is opened by post method, then location.reload will result in a prompt message.

For example, if a user is taken to a page after a form is submitted where form used the Post method, then above examples will throw an alert before refreshing the page.

For avoiding that, you may use the window.location.pathname as shown in the demo below:

javascript refresh post

See online demo and code

The JavaScript code:


You should only use this technique for the pages loaded after post method and it will also remove the query string as in the demo.

This div height required for enabling the sticky sidebar