Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Can I Hide a Loading Overlay When User Returns to Page via Back Button

Background

To ease page transitions on my web app, I'm building in an overlay/loading icon layer. It is visible initially, and I hide it after my JS is finished loading. I then show it when any a elements are clicked. Screencap below:

enter image description here


Code

HTML

    ...
</head>
<body class="preload">
    <loading><div class="pulse-loader visible"></div></loading>

Hide on Page Load

setTimeout(function(){
    $("body").removeClass("preload");
}, 120);

Show on Click

$('body').on('click', 'a', function(event){
    $("body").addClass("preload");
});

Goal

When the user clicks the back button, I'd like for the page to realize that and re-hide the loading overlay/icon. Is this possible?

like image 731
Andy Mercer Avatar asked Jan 26 '26 01:01

Andy Mercer


1 Answers

Answer

The answer is the pageshow/pagehide events. WebKit introduced these, in part to deal with this exact problem. There is a load, and unload event. I only need the load event for my purposes, though I could use the unload even to show my loading overlay.

Code

I place this in my script file (both inside or outside of the jQuery document.ready wrapper):

if ("onpagehide" in window) {
    window.addEventListener("pageshow", function() {
        setTimeout(function(){ $('body').removeClass('preload');  }, 120);
    }, false);
} else {
    window.addEventListener("load", function() {
        setTimeout(function(){ $('body').removeClass('preload'); }, 120);
    }, false);
}

The pageLoaded function is fired on page load, even when the page is reached via the back button.

Browser Compat:

I've tested this in Edge, Firefox, on Windows, and Safari on OSX, and it works.

EDIT:

This is currently broken in Chrome. There's a bug ticket, but it hasn't had much movement recently. If you'd like to see it fixed, upvote the ticket!

like image 96
Andy Mercer Avatar answered Jan 27 '26 15:01

Andy Mercer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!