JavaScript: Refresh Page
Sometimes you need to refresh a webpage using JavaScript. If the need arises, use the location object to use the
reload()
method.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>repl.it</title> <link href="style.css" rel="stylesheet" type="text/css" /> </head> <body onload="handleLoad()"> <button id="btn">Click Me!</button> <script> let arrayKittens = [ "http://placekitten.com/200/300", "http://placekitten.com/210/310", "http://placekitten.com/300/300", "http://placekitten.com/300/200", "http://placekitten.com/310/210", "http://placekitten.com/400/300"]; let button = document.querySelector("#btn"); button.style.display = "block"; button.style.margin = '20px 0px' const handleClick = (e) => { console.log("click") location.reload(true); } button.addEventListener("click", handleClick); let body = document.querySelector("body"); let image = document.createElement("img"); const handleLoad = (e) => { console.log("loaded") let random = Math.floor(Math.random() * arrayKittens.length); let newImg = arrayKittens[random]; image.setAttribute("src", newImg); image.setAttribute("width", "300"); image.setAttribute("height", "300"); image.setAttribute("alt", " arrayKittens[" + random + "]"); image.style.objectFit = "cover"; body.appendChild(image); }; </script> </body> </html>
There are two event listeners in this document. The first happens when the page loads to add an
<img />
to the DOM. The second contains our
reload()
function. When a user clicks on “Click Me!”, the page will reload by triggering the
handleClick()
function. This page uses JavaScript to handle just about all of our logic.
In this particular example, a random cat picture from an array of cat pictures will display each time the page reloads.

Find Your Bootcamp Match
- Career Karma matches you with top tech bootcamps
- Access exclusive scholarships and prep courses
By continuing you agree to our Terms of Service and Privacy Policy , and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.
The true or false value passed in will indicate whether or not the page is reloaded from the server or from the browser cache. The default value is false, which reloads the page from the cache, so there is no need to pass a value in unless you want to reload the page from the server.
That’s all there is to it!