auto-refresh page once only after first load – Using JavaScript / JQuery

In this Javascript How-To Tutorial, we are going to learn a very useful technique. We will discuss multiple ways to One-time page refresh after the first-page load automatically using Javascript or JQuery.

Javascript can be very useful for Frontend and Backend Development, The one language to rule them all, as they say.

Let’s consider Your Developing Some API based web app and for testing purposes, you need to reload web page after fully loading once and you want to do it using Javascript/jQuery.This is just one example, there can be any reason you want to achieve this.First, we learn to reload once using javascript.

How to Auto-refresh page once only after the first load Using Javascript

Using window.onload:


/add this js script into the web page,
//you want reload once after first load
window.onload = function() {
    //considering there aren't any hashes in the urls already
    if(!window.location.hash) {
        //setting window location
        window.location = window.location + '#loaded';
        //using reload() method to reload web page


Using window.localStorage:


//we will auto-triggering js function
//to refresh once after first load
  if( window.localStorage )
    //check if reloaded once already 
    if( !localStorage.getItem('firstLoad') )
     //if not reloaded once, then set firstload to true
      localStorage = true;
      //reload the webpage using reload() method


How to Auto-refresh page once only after the first load Using JQuery

First Method:


//this method is simialr to first js method above
//Jquery initialize
    //Check if the current URL contains '# or hash'
        // Set the URL to whatever it was plus "#loaded".
        url = document.URL+"#loaded";
        location = "#loaded";

        //Reload the page using reload() method


The second method using cookie:

body onload='if(document.cookie.indexOf("refreshcookie") == -1){

Using the localStorage method in JQuery:


//modily according to your requirement
  document.body.innerText = 'checking';
  if (localStorage.getItem('isLoaded') !== 'yes') {
    localStorage.setItem('isLoaded', 'yes');
    alert('reloading now');
        document.body.innerText += ' - loaded once';
  } else {
    alert('not reloading');
        document.body.innerText += ' - loaded twice';

All these code snippets are tested and working, you can use any snippet and achieve the same result of js relad once after the first load. If you have queries, please comment below or if you have any other code snippet, please share below and we will add to the article with credits.

About the author

Vithal Reddy

Vithal Reddy is a seasoned technology professional with expertise in Full Stack Web development, Micro services and Scaling infrastructure on Cloud.
More at