Created
October 7, 2024 12:31
-
-
Save brianfeister/859ae7d7a05e21443dbe1a3cce41e33e to your computer and use it in GitHub Desktop.
Show a loading indicator in page transitions for multi-page apps
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script> | |
let loadingBarInterval; | |
function showLoadingIndicator() { | |
const existingBar = document.getElementById('top-loading-bar'); | |
if (existingBar) { | |
existingBar.remove(); | |
} | |
const loadingBar = document.createElement('div'); | |
loadingBar.id = 'top-loading-bar'; | |
loadingBar.style.position = 'fixed'; | |
loadingBar.style.top = '0'; | |
loadingBar.style.left = '0'; | |
loadingBar.style.width = '0%'; | |
loadingBar.style.height = '3px'; | |
loadingBar.style.backgroundColor = '#00ff00'; | |
loadingBar.style.transition = 'width 0.3s ease-out'; | |
loadingBar.style.zIndex = '9999'; | |
document.body.appendChild(loadingBar); | |
let progress = 0; | |
loadingBarInterval = setInterval(() => { | |
progress = progress + (100 - progress) / 2; | |
loadingBar.style.width = `${progress}%`; | |
if (progress > 99.9) { | |
clearInterval(loadingBarInterval); | |
} | |
}, 1000); | |
} | |
function hideLoadingIndicator() { | |
const loadingBar = document.getElementById('top-loading-bar'); | |
if (loadingBar) { | |
clearInterval(loadingBarInterval); | |
loadingBar.remove(); | |
} | |
} | |
window.addEventListener('pageshow', (event) => { | |
if (event.persisted) { | |
// This page is restored from browser's cache | |
hideLoadingIndicator(); | |
} | |
}); | |
document.addEventListener('click', (event) => { | |
const target = event.target.closest('a'); | |
if (target && target.href && !target.target && !event.ctrlKey && !event.metaKey) { | |
showLoadingIndicator(); | |
} | |
}); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment