Skip to content

Instantly share code, notes, and snippets.

@stenito
Last active January 10, 2022 13:24
Show Gist options
  • Save stenito/fb76fc64c716cf8cb1a3ec31c4c41e15 to your computer and use it in GitHub Desktop.
Save stenito/fb76fc64c716cf8cb1a3ec31c4c41e15 to your computer and use it in GitHub Desktop.
Add an overlay to a HTML page until all fonts are loaded.
/* Add to head style tag */
[data-loadscreen] {
opacity: 1;
z-index: 10000;
width: 100vw;
height: 100vh;
position: fixed;
top: 0;
left: 0;
/* optional */
background-color: #ffffff;
display: flex;
justify-content: center;
align-items: flex-start;
padding: 2em;
text-align: center;
overflow-y: scroll;
font-family: sans-serif;
/* /optional */
}
[data-loadscreen].hidden {
pointer-events: none;
display: none !important;
top: -100vh !important;
}
body.noscroll {
/* Stops the scroll on everything behind the overlay. This is removed when JavaScript is available. */
overflow: hidden;
}
<!-- Add to page after body tag -->
<div data-loadscreen>
<!-- optional -->
<div>
<noscript>Any content you want to show when no JS</noscript>
<div>
<!-- /optional -->
</div>
// Execute JS just before body close tag.
const loadScreen = document.querySelector("[data-loadscreen]");
if (loadScreen) {
document.fonts.ready.then(function () {
loadScreen.classList.add("hidden");
document.body.classList.remove("noscroll");
});
} else {
console.error("ERROR => loadscreen.js: no [data-loadscreen] element found on page.");
}
@stenito
Copy link
Author

stenito commented Jan 10, 2022

Loadscreen

To avoid flash of anything (FOUT, FOIT, FOFT) when using web-fonts, showing an overlay until fonts are loaded is another option.

The overlay hides the rendered page until all fonts are loaded. It is a choice and depends on wether you prefer flashing text and layout shifting or letting the visitor wait a little (a few 100 milliseconds on an average connection) until content can be rendered with the used web-fonts.

Since connections are getting faster, I prefer a very short wait over layout shifting.

Noscript

I use the overlay to show noscript content.

In (the very unlikely) case that a visitor has no JS, the overlay will stay in place and I can still show attractive content.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment