Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait for fonts to load before rendering web page

I'm using @font-face to embed fonts in my website. First the text renders as the system default, and then (once the font file has loaded presumably) the correct font renders a fraction of a second later. Is there a way to minimise/get rid of this delay, by delaying the page rendering until after fonts have loaded or similar.

like image 822
wheresrhys Avatar asked Jan 17 '11 10:01

wheresrhys


People also ask

Should you preload fonts?

In summary, without font preloading, you might run into a situation where a browser is ready to load your site's text, but it can't because the font isn't available yet. That is, it needs to download the font before it can paint the text.


2 Answers

Since nobody mentioned that, I believe this question needs an update. The way I managed to solve the problem was using the "preload" option supported by modern browsers.

In case someone does not need to support old browsers.

<link rel="preload" href="assets/fonts/xxx.woff" as="font" type="font/woff" crossorigin> 

some useful links with more details:

https://developer.mozilla.org/en-US/docs/Web/HTML/Preloading_content http://www.bramstein.com/writing/preload-hints-for-web-fonts.html

like image 176
Thiago C. S Ventura Avatar answered Sep 25 '22 14:09

Thiago C. S Ventura


Edit: The best approach is probably to base64 encode your fonts. This means your font will have to be loaded fully by the time your HTML is parsed and displayed. You can do this with font squirrel's webfont generator https://www.fontsquirrel.com/tools/webfont-generator by clicking "Expert" and then "base64 encode". This is how services like TypeKit work.


Original answer: Another way to detect if fonts are loaded would be using FontLoader https://github.com/smnh/FontLoader or by copying their strategy.

They bind to the scroll event in the browser, because when the font loads it will resize the text. It uses two containing divs (that will scroll when the height changes) and a separate fallback for IE.

An alternative is to check the DOM periodically with setInterval, but using javascript events is far faster and superior.

Obviously, you might do something like set the opacity of body to 0 and then display it in once the font loads.

like image 22
Ryan Taylor Avatar answered Sep 22 '22 14:09

Ryan Taylor