Execute JavaScript function when the page is being refreshed or accessed from an external link

On the Home page, we have a special Lottie animation that serves as a preloader. This animation should only display under certain conditions:

  1. Accessing the home page by clicking on a link from an external page (not on your website)
  2. Refreshing the browser
  3. Entering the URL in the browser's address bar

However, we DO NOT want the animation to show when:

  1. Clicking on a link from an internal page (on your website)
  2. Navigating through the browser's previous/next history buttons.

    <script src="https://code.jquery.com/jquery-3.6.3.min.js" integrity="sha256-pvPw+upLPUjgMXY0G+8O0xUf+/Im1MZjXxxgOcBQBXU=" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bodymovin/5.7.4/lottie.min.js"></script>
    
    <div id="preloader">
        <div class="logo" id="home-preloader"></div>
    </div>
    
    <style>
      /* Some styling here */
    </style>
    
    <script>

    function playPreloader() {
      var animation = bodymovin.loadAnimation({
        container: document.getElementById('home-preloader'),
        path: 'preloader.json',
        renderer: 'svg',
        loop: false,
        autoplay: true,
        name: "Home Preloader",
      });
    }
    
    </script>

Looking for suggestions on how to achieve this? I've attempted using PerformanceNavigation.type and PerformanceNavigationTiming.type without success. While I'm not particularly proficient in JavaScript, I can work with some guidance.

Even if I could make it work, distinguishing between external and internal links still seems to be an issue.

window.addEventListener("load", function() {

  var performance = window.performance || window.webkitPerformance || window.msPerformance || window.mozPerformance;
  var navigation = performance.getEntriesByType("navigation")[0];

  if (navigation.type === "navigate") {
    console.log("The page was accessed by following a link, a bookmark, a form submission, or a script, or by typing the URL in the address bar.");
  } 
  else if (navigation.type === "reload") {
    console.log("The page was accessed by clicking the Reload button or via the Location.reload() method.");
    playPreloader();
    yesPreloader();
  } 
  else if (navigation.type === "back_forward") {
    console.log("The page was accessed by navigating into the history.");
    noPreloader();
  } 
  else {
    console.log("Any other way.");
  }
});

Answer №1

After dedicating two full days to research, I stumbled upon a comment that proved to be extremely helpful in solving my issue. In the spirit of sharing knowledge, here is the code snippet for anyone facing a similar problem.

If someone could validate the correctness of this solution, it would be greatly appreciated.

/* (0) WHEN THE PAGE LOADS */
window.addEventListener("load", function() {

    /* (1) DETERMINE THE ACCESS METHOD OF THE PAGE */

    var result;
    var p;

    if (window.performance.navigation) {
        result = window.performance.navigation;
        
        if (result == 255) {
            result = 4;
        }
    }

    if (window.performance.getEntriesByType("navigation")) {
        p = window.performance.getEntriesByType("navigation")[0].type;

        if (p == 'navigate') {
            result = 0;
        }
        
        if (p == 'reload') {
            result = 1;
        }
        
        if (p == 'back_forward') {
            result = 2;
        }
        
        if (p == 'prerender') {
            result = 3;
        }
    }

    console.info(result);

    /* (2) ACTIONS FOR EACH SCENARIO */

    if (result == 0) {
        console.info("Page was accessed from a link or address bar");
        console.info("Result was 0, result=" + result);

        if (document.referrer.indexOf(location.hostname) !== -1) {
            console.info("Page was accessed from an internal link");
            $(document).ready(function() {
                noPreloader();
            });
        } else {
            console.info("Page was NOT accessed from internal link. Probably accessed from an external link or address bar");
            $(document).ready(function() {
                $(this).scrollTop(0);
                document.body.classList.add("overflow-x-hidden");
                document.body.classList.add("overflow-y-hidden");
                playPreloader();
                yesPreloader();
            });
        }

    } else if (result == 1) {
        console.info("Page was accessed by reloading (browser reload operation)");
        console.info("Result was 1, result=" + result);
        $(document).ready(function() {
            $(this).scrollTop(0);
            document.body.classList.add("overflow-x-hidden");
            document.body.classList.add("overflow-y-hidden");
            playPreloader();
            yesPreloader();
        });

    } else if (result == 2) {
        console.info("Page was accessed from the browser history back or forward buttons");
        console.info("Result was 2, result=" + result);
        $(document).ready(function() {
            noPreloader();
        });
    } else {
        console.info("Page was accessed: Any other instance (prerender or 255)");
        console.info("Result was probably 255 (4) or prerender (3), result=" + result);
        $(document).ready(function() {
            noPreloader();
        });
    }

});

/* [END] (1) WHEN THE PAGE LOADS */

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

Tips for capitalizing the first letter of a directory

I want to automatically convert all directories in the URI to lowercase if the user types them in uppercase. For example, https://example.com/hOmE should be converted to https://example.com/home. ...

PHP distributing empty sheets (possibly for website configuration)

Hey everyone! I've been struggling to set up a profile page on my website for the past week. Whenever I try to include PHP code or echoes in the content pages, I either get blank pages or encounter a 500 server error. My website is structured with a ...

Exploring different ways to make API requests using technologies like jQuery, Angular, and more

I'm new to APIs and I want to create an eco game with Facebook for London and Amsterdam. To do this, I need to obtain data from APIs in each city. After doing some research, I think I can request information on the client side of the app, process it, ...

Navigating through the realm of Android development entails understanding how to manage a multi-object function in JavaScript when using

In order to load an HTML page using the webview component and handle its functions, I am faced with a challenge. The HTML page contains a multi-object named (webkit.messageHandlers.adClicked). How can I utilize the webView.addJavascriptInterface() functi ...

What's the deal with z-index not functioning properly?

Below is my simple HTML and CSS code: HTML: <div class="header"> <div class="tip"></div> </div> CSS: .header { display: block; width: 260px; min-height: 222px; background-color: #252525; position: relati ...

Creating Eye-Catching Titles with HTML and CSS

As a beginner in HTML and CSS, I'm curious about creating an eye-catching header on a website with a different background than the rest of the page. Is it possible to achieve this effect using HTML and CSS? Apologies if this question sounds silly. T ...

Troubleshooting Tips: Removing a Specific Line from a Canvas Using Javascript

I need to find a method for removing a specific line without having to clear and redraw it. Learn more about clearing specific lines in Canvas with HTML5 I came across this question where everyone suggested clearing the entire page and redrawing it. Is t ...

Vue3 - Implementing a seamless communication channel between two child components

Vue 3 has brought about changes in my component structure, as shown below: https://i.sstatic.net/bgtPB.png In this setup, ChildA can communicate with ChildB and requires ChildB to update its state accordingly. In Vue 2, I could send an event from ChildA: ...

An effective method for converting a string into a two-dimensional array using JavaScript

One challenge I am facing is checking from a string if a specific fruit has the correct amount on a given date. I've managed to achieve this by converting the string into a 2D array and iterating over the columns. While this method works, I can't ...

Creating a running text (marquee) with CSS is a simple and efficient way to make

I encountered a significant challenge while delving into CSS animation. My goal is to create a "transform: translate" animation that displays text overflowing the content width as depicted in the image below. https://i.stack.imgur.com/sRF6C.png See it i ...

What is the process for utilizing jQuery and ajax to retrieve data from a MySQL database?

I am currently working on a form that includes a "select" box. The goal is to display the relevant records from the database on the same page once an option is selected. This process involves two files: an HTML page containing the form: <form id="theF ...

Stream data's modification to numerous controllers post ajax loading

One issue I encountered in my Angular app is related to the asynchronous loading of data from a server. Some controllers depend on this data, which is retrieved through an AJAX request. The problem arises because controllers end up pointing to an empty arr ...

Upon initiating a React Native project, five critical vulnerabilities become apparent

Upon starting my React Native project, I encountered 5 high severity vulnerabilities. Despite attempting to fix them with the command "npm audit fix --force", the issue persisted. I even went as far as reinstalling node.js and React Native, but the vulne ...

Loading dynamic fonts in React MaterialUI

In our web application, each user experiences a unique style with colors, fonts, border widths, and more based on the Material UI JSON theme retrieved from the database upon loading the app. The challenge lies in handling dynamic fonts. What approaches ha ...

The server's request is being processed through jQuery's ajax functionality

Recently, I've started working with jQuery and AJAX. Essentially, the webpage sends an HTTP post request, and the server-side DLL responds by writing a JSON-formatted response back to the page. I'm trying to understand how to handle this response ...

Customize the behavior of the focus-visible feature on input elements

In my design, I want to remove the outline ring on an input element when it's focused via mouse interaction but still keep it visible when focused using the keyboard. This similar question was raised about a week ago here, unfortunately with no solut ...

I am interested in accessing a file located on my D: drive through the use of AJAX

The file I uploaded can be found at D:\eclipseworkspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\DatasetFileUpload\myNewFolder However, I am having trouble reading a file from the above locati ...

Why isn't the response entity being returned following the ajax call?

So, I have a question regarding my attempt to send a simple post request to my controller using an URL as the post body. However, upon completion of the ajax call, I am not receiving any response from the controller. What could be causing this issue? Let ...

Utilize JavaScript destructuring to assign values to a fresh object

When working with JavaScript/Typescript code, what is a concise way to destructure an object and then assign selected properties to a new object? const data: MyData = { x: 1, y: 2, z: 3, p: 4, q: 5 } // Destructuring const { x, z, q } = data; // New O ...

How to use jQuery to target every anchor element within an unordered list

I am trying to manipulate an unordered list structure by changing the class of the anchor tags when a specific link is clicked. For example, when the link in List Item 1 is clicked, I want to change the class of all links underneath List Item 1 to "yes". ...