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:

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");
});
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?
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.
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With