Can you see font is changing from default
to expected font? That's called FOUT (Flash of Unstyled Text). This happend cause your browser is rendered element before your font has loaded. It makes your website look cheap and you look like a beginner. π
Be grateful because in 2021 there is already an API to solve this problem. The name is FontFaceSet API, you can check the documentation here.
Let's get started!
#0 FYI
I am using fontsource
to import my external font. Just because, I am using the gatsby
framework. It doesn't matter what you use, because this method works on any framework. Including the non-react framework.
import "@fontsource/merriweather"
#1 Create state
const [isReady, setIsReady] = useState(false);
First we create a state
to store the state whether the website is ready to render or not.
return (isReady &&
<div>
{/* Your component goes here */}
</div>
)
Don't forget to add a condition if the state shows it's not ready, then don't render the element.
#2 Check & Load fonts
To check the font we use FontFaceSet
as follows:
useEffect(() => {
document.fonts.load("12px Merriweather").then(() => setIsReady(true));
}, [])
Merriweather
is fontface name, you can change that. 12px
is dummy fontSize
to check. The following line of code is a Promise so that we can add commands when the font has been successfully loaded.
#3 And wallaaaaa...
Thanks for your time to read this post. This is my first post on dev.to
, i hope i can keep on writing on this platform π . If you don't mind please give a reaction to support me. π
Top comments (4)
Could another issue be that search engine crawlers might not work properly? Because of the delay?
Yes, SEO also have some bugs because of the delay. After i implement this method, i think best way to handle FOUT problem is configurating the default font. So user can see other default font that look similar with your styled font. Maybe i will update my post. Thanks for asking π
Well, the downside of this technique is higher loading time. Is there a way to swap the font, like swaps placeholder image with the real one?
Yeah, maybe for better UX i think that technique can combine with
skeleton
component. It will better than just wait without 'loading indicator'. Thanks for the comment.