Determining when a webpage first loads vs. being refreshed in JavaScript

I require the execution of a JavaScript function to occur after a web page has been refreshed, regardless of the method used (such as pressing F5, clicking the browser's refresh button, or re-entering the same URL). This action should only take place upon a page refresh, not during the initial page load.

Something along these lines:

window.onrefresh = function() { ... }; // of course, 'onrefresh' is not a real event

While I have come across some solutions on the web, none of them entirely meet my requirements:

Dirty Flag

This approach is quite straightforward - upon loading, check for a flag. If the flag does not exist, it signifies the first load, otherwise set the flag:

  • Store the flag in either local storage or a cookie. The flag could be based on the current Date/Time. If the flag is not present on load, create it - indicating the first load. Otherwise, compare it with the current Date/Time after the refresh.
  • Include the flag in the site's URL by using the '#' symbol ('#' will not alter site navigation). Similar to before, test for the presence of '#' at the end of the URL on load; if found, it indicates a "refresh" load, if not, this is the first load - thus add a '#' to the end of the URL.

performance.navigation

The window object features the property:

window.performance.navigation.type
, which can have 3 possible values:
0 - Page loaded due to a link
1 - Page reloaded
2 - Page loaded due to the Back button
Nevertheless, this solution does not function as expected. The value returned is always "1", irrespective of whether it is the initial load or a refresh.

Answer №1

Utilize the Navigation Timing API to collect performance data on the client side, which can then be sent to a server using XMLHttpRequest or other methods. The Performance object provides access to browser performance and timing information.

We achieve this by leveraging the Navigation Timing API. The primary interface of the Navigation Timing API for your needs is performance.navigation.type, which determines whether the URL is being loaded in the browser for the first time or if it's a reload. Below is an example:

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
 <head>
    <meta charset="utf-8" />
    <title></title>

    <script>
        if (window.performance) {
            alert("Browser Supports");
        }
        if (performance.navigation.type === 1) {
            alert("Reloaded"); 
        } else {
            alert("Not Reloaded"); 
        }
    </script>
 </head>
 <body>
    <h2>testing</h2>
 </body>
</html>

I hope this solution proves helpful for you.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the reason for AngularJS not utilizing the most recently assigned value?

<html> <head> <title>Test</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="angul ...

What could be causing React to throw an invalid hook error when using useRoutes?

I encountered an error while attempting to add a new route to my project. import React from "react"; import News from "./NewsComponents/News"; import Photos from "./PhotosComponents/Photos"; import Contact from "./Contact"; import Home from "./Home"; ...

Utilizing HTML5 data attributes to store intricate JSON objects and manipulate them using JavaScript

Recently, I encountered a unique challenge that I set for myself... I am currently in the process of developing an advanced ajax content loader plugin that comes with an array of options and callbacks. In order to streamline the initialization process and ...

bcrypt is failing to return a match when the password includes numeric characters

I've integrated node-bcrypt with PostgreSQL (using Sequelizejs) to securely hash and store passwords. In the process, the user's password undergoes hashing within a beforeValidate hook as shown below: beforeValidate: function(user, model, cb) { ...

Creating a stunning image carousel in Vue by integrating a photo API: step-by-step guide

Trying to figure out how to create an image carousel in Vue using photos from an API. Currently able to display the photos using: <section class="images"> <img v-for="image in images" :key="image.id":src="image.assets.large.url"> &l ...

Invoking a function in a Node.js backend from an Angular frontend application

Currently, I'm working on an angular application (angular-seed app) that needs to trigger a function located in a Node.js file (web-server.js). This particular function is responsible for executing a batch file. ...

Top tips for resolving Swiper Js initial loading issues in a Carousel!

After implementing swiper js from , I encountered an issue. The initial loading displays only a single carousel item before the rest start appearing, creating a glitchy effect. To clarify, when the website is loaded, only the first item is visible in the ...

How can I retrieve data using the angular method instead of the traditional $.ajax approach? Is $http a suitable replacement for $.ajax in Angular?

Here is the code snippet I have written. .state("dynamic", { url: "/:name", controller : 'AppHomeCtrl', templateUrl: function (params){ var myURL = params.name + '.html'; var validPage ...

The issue persists with UIkit modal element remaining in the DOM even after the parent component in Vue.js is destroyed

In my Vue app, I am utilizing the UIKit modal. UIkit.modal(element).show(); // This adds the class uk-open and sets style to display:block UIkit.modal(element).hide(); When I hide the modal, it simply removes the class uk-open and the inline style of dis ...

Restrict the input to only allow for parentheses, disallowing any letters or numerical characters

Only parentheses are allowed in the input field; letters and numbers will not be accepted. function checkBrackets() { var inputVal = document.getElementById("input").value; var result = document.getElementById("strong").value; console.log(inputVal, ...

Is there a way for me to limit my usage of the async keyword in my code

Consider the scenario outlined below, using Javascript: Deep within the call stack, Something transforms into a Promise This transformation can occur due to various reasons. // a calls b, calls c, and so on. function z(){ // Let's assume this ...

Tips for disabling the default behavior by using preventDefault in JavaScript

I need help with removing the preventDefault() function and submitting the form in the else condition of my code. Does anyone know how to achieve this? if(email.val() != ""){ //check email e.preventDefault(); $.ajax({ ...

Loading Java Script files in real-time

Is there a method to dynamically load JS files before "$(document).ready" is triggered, while still having them available in the ready event handler? Is there a feature in jQuery that allows for this process? The challenge I am facing involves loading di ...

What is the best way to retrieve user data for showcasing in a post feed using firebase's storage capabilities?

I'm currently developing a forum-style platform where users can share content that will appear on a universal feed. I intend to include user details in the posts (such as photoURL and displayName) similar to how it is done on Twitter. For this projec ...

What measures do websites such as yelp and urbandictionary implement to avoid multiple votes from unregistered users?

It is interesting to note that on urbandictionary, you do not need to be logged in to upvote a definition. For example, if you visit and upvote the first word, it will record your vote. Even if you open an incognito window and try to upvote again, or use ...

What could be causing the removeChild() method to fail when trying to delete a list item in JavaScript DOM manipulation?

Check out this interactive shopping list. You can add items, delete them, and mark them as completed. Adding and deleting items works fine, but there's an issue when toggling them. Issue (occurs when toggling multiple list items) If you add 3 items ...

Include criteria in my ajax call (conditional statements)

Is there a way to add conditions to my ajax request? Whenever I include the code below, it only seems to work for one item at a time. $.ajax({ type: 'GET', url: urlPost, success: function (data) { $.each(data, function (key, value) { ...

Having trouble with Express router behaving unexpectedly in a subdirectory

In my Node.js app, I have organized my API queries by modules. This structure is reflected in the index.js file as follows: app.use('/api/schedule/', apiSchedule); Within the apiSchedule router, I have defined different route handlers: router. ...

Encountering Errors with Angular JS Following Update from Version 1.1.0 to 1.1.1

After upgrading, I noticed that the ng-repeat function is taking significantly longer to load and is attempting to display additional content boxes without serving the actual content provided by $resource. I have pinpointed the issue to the update from ve ...

Fill in a Checkbox

I'm looking to display a checkbox field within a gridview. Currently, I am using the Checked='<%# Convert.ToBoolean(Eval("Inactive")) %>' statement. However, I've encountered an issue where some records in the database have a NUL ...