This code creates and manages a preloader element, designed to...
This code creates and manages a preloader element, designed to show a brief loading indicator on a webpage while the page is being loaded or processed. Here's what each part of the code does:
HTML
-
<div class="ExtPreloader" role="status" aria-live="polite" aria-label="Loading">
- This
<div>
element acts as the preloader. It includes:- Accessibility roles to communicate its purpose (e.g.,
role="status"
,aria-live="polite"
,aria-label="Loading"
). - An image (
img
) inside the<div>
that displays a logo (CYME Copenhagen.svg
) representing the preloader graphic. - The image is optimized for async decoding (
decoding="async"
) and has afetchpriority="low"
to ensure it does not hinder the loading of more critical resources.
- Accessibility roles to communicate its purpose (e.g.,
- This
-
Fallback
<noscript>
block:- If JavaScript is disabled, the preloader is not displayed (
.ExtPreloader{display:none!important}
).
- If JavaScript is disabled, the preloader is not displayed (
JavaScript (Preloader Behavior)
1. Initialization
-
p=document.querySelector('.ExtPreloader');
- Fetches the preloader
<div>
via its class.
- Fetches the preloader
-
if(!p) return;
- Stops execution if the preloader element is not found.
2. Define Timing and Behavior
-
start=performance.now();
- Records the time when the script starts running to calculate how long the preloader has been displayed.
-
Predefined time limits:
min=350
ms (minimum display time) andmax=550
ms (maximum display time). This ensures the preloader is displayed for a perceptible amount of time.- Uses
navigator.connection.saveData
to reduce these times on devices with data-saving mode enabled.
3. Preloader Removal Logic
remove()
- Hides the preloader (
aria-hidden="true"
, addshidden
class) and removes it from the DOM after a short delay (200 ms).
- Hides the preloader (
4. Automatic Preloader Removal
-
Sets a
maxT
timeout to ensure the preloader is forcibly removed after the maximum display time (max
). -
If the page finishes loading sooner:
done()
calculates the remaining time to ensure the preloader is displayed for at leastmin
milliseconds.- Then removes the preloader and cancels the
maxT
timeout.
5. Event Listener for Page Load
-
If the page is fully loaded already (
document.readyState === 'complete'
), it immediately removes the preloader viadone()
. -
If the page is still loading, it adds a
load
event listener to triggerdone()
once loading completes.
Overall Functionality
- The preloader ensures a smooth user experience:
- It displays a visual loading indicator for at least a minimum amount of time and automatically removes itself once the page is ready or after a maximum period.
- It also accounts for users who have data-saving modes enabled by reducing the display time.
- It ensures accessibility for screen readers and has fallbacks for when JavaScript is unavailable.