I have a div overlay that shows a loading gif. When the page is loaded, the div overlay is supposed to disappear.
<div id="posts">
<div id="loading" style="display: none;">
<img id="loading-image" src="/loading.gif" alt="Loading...">
</div>
<div>
...
</div>
</div>
To hide the div overlay, I was using:
$(window).on('load', function () {
// hide loading div
$('#loading').hide();
})
In Chrome, if I navigate to some link, then navigate "back", the loading div overlay doesn't hide. It only hides when I reload the page.
If I add unload or beforeunload to the jQuery event list, I get the behavior I want, but unload is deprecated and beforeunload will likely cause cache problems and performance issues.
The way I understand it, a load event isn't triggered when a user hits "back".
But I want the div overlay to disappear when page is loaded OR when user hits back to page.
How can I achieve this without taking a performance hit?
I've tried DomContentLoaded with regular js.
window.addEventListener('DOMContentLoaded', function() {
let loading = document.querySelector('#loading');
loading.style.display = 'none';
console.log('Loaded');
})
"Loaded" prints in the console, but the overlay has an empty style tag, like so:
<div id="loading" style>...</div>
window.addEventListener('pageshow', function() {...} seems to work but I'm not sure if it will cause a performance hit or if it's the best solution. Never used it before.
Is this a Chrome thing? Is there a Chrome setting I should look at? I test in MS Edge and Firefox and $('#loading').hide(); works fine on load and back navigation.
Chrome version: Version 101.0.4951.67 (Official Build) (64-bit)
Even this logs to the console but doesn't hide the div in Chrome!
$(document).ready(function () {
$('#loading').hide();
console.log('Should be hidden?')
})
Edit
By default, CSS displays this overlay with display: block;. When the page loads, I set this CSS property to none to hide it.
#loading {
width: 100%;
height: 100%;
top: 0;
left: 0;
position: absolute;
display: block;
opacity: 0.7;
background-color: #fff;
z-index: 99;
text-align: center;
}
#loading-image {
position: fixed;
top: 50%;
left: 50%;
z-index: 100;
transform: translate(-50%, -50%);
}