Search code examples
javascripthtmljquerycsslottie

Run JavaScript function only if you're refreshing the page or coming to the page from external link


We have a Lottie animation that should act as a preloader and show only on the Home page.

We want to SHOW this when accessing the home page by:

  1. clicking on a link from an external page (not on your website)
  2. clicking refresh on the browser
  3. when entering the URL in the browser's address bar.

We DON'T want to show the animation when

  1. clicking on a link from an internal page (on your website)
  2. navigate through the browser's prev/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>

Any ideas on how to do it? I tried a few things with PerformanceNavigation.type and PerformanceNavigationTiming.type but couldn't manage to figure it out. I'm not very skilled in JavaScript, but can manage things if I can have direction.

Even if this worked, it doesn't seem to differentiate between external and internal links.

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.");
  }
});

Solution

  • After researching for two days, I found a comment that was very helpful and helped me create a working solution to my problem. Here's the code for anyone having the same problem.

    If somebody can confirm that all of this is correct, that would be nice.

    /* (0) WHEN THE PAGE IS LOADED */
    window.addEventListener("load", function() {
    
        /* (1) FIND HOW THE PAGE WAS ACCESSED */
    
        var result;
        var p;
    
        if (window.performance.navigation) {
            result = window.performance.navigation;
            // 255
            if (result == 255) {
                result = 4
            }
        }
    
        if (window.performance.getEntriesByType("navigation")) {
            p = window.performance.getEntriesByType("navigation")[0].type;
    
            // Page was accessed from a link or address bar
            if (p == 'navigate') {
                result = 0
            }
            // Page was reloaded (browser reload operation)
            if (p == 'reload') {
                result = 1
            }
            // Back or Forward (browser history)
            if (p == 'back_forward') {
                result = 2
    
            }
            // Prerender
            if (p == 'prerender') {
                result = 3
    
            }
        }
    
        console.info(result);
    
        /* (2) WHAT TO DO IN EACH CASE */
    
        if (result == 0) {
            // Page was accessed from a link or address bar
            console.info("Page was accessed from a link or address bar");
            console.info("Result was 0, result=" + result);
    
            // Was it an internal link or (external link or address bar)
            if (document.referrer.indexOf(location.hostname) !== -1) {
                // Page was accessed from an internal link
    
                console.info("Page was accessed from an internal link");
                $(document).ready(function() {
                    noPreloader();
                });
            } else {
                // Page was NOT accessed from internal link
                // Probably accessed from external link or address bar
                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) {
            // Page was reloaded (browser reload operation)
            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) {
            // Back or Forward (browser history)
            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 {
            // Any other instance
            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 OF] (1) WHEN THE PAGE IS LOADED */