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 render
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
This code works very well for me. It uses the Font Loading API which has good support among modern browsers.
<style>
@font-face {
font-family: 'DemoFont';
font-style: normal;
font-weight: 400;
src: url("./fonts/DemoFont.eot");
src: url("./fonts/DemoFont.woff2") format("woff2"),
url("./fonts/DemoFont.woff") format("woff"),
url("./fonts/DemoFont.ttf") format("truetype");
}
.font {
font-family: 'DemoFont';
color: transparent;
}
html.font-loaded .font {
color: inherit; // Override `transparent` from .font
}
</style>
<script>
// Check if API exists
if (document && document.fonts) {
// Do not block page loading
setTimeout(function () {
document.fonts.load('16px "DemoFont"').then(() => {
// Make font using elements visible
document.documentElement.classList.add('font-loaded')
})
}, 0)
} else {
// Fallback if API does not exist
document.documentElement.classList.add('font-loaded')
}
</script>
The trick is to set the CSS color to transparent for elements using the font. Once loaded this is reset by adding font-loaded
class to <html>
element.
Please replace DemoFont
with something meaningful for your project to get it work.
Use https://github.com/typekit/webfontloader
and check the events in the configuration https://github.com/typekit/webfontloader#configuration
<script src="https://ajax.googleapis.com/ajax/libs/webfont/1.6.26/webfont.js"></script>
<script>
WebFont.load({
custom: {
families: [ "CustomFont1", "CustomFont2" ]
},
active: function() {
//Render your page
}
});
</script>
Only IE loads first the font and then the rest of the page. The other browsers load things concurrently for a reason. Imagine that there's a problem with the server hosting the font or with the font downloading. You will hang your entire site until the font is loaded. On my opinion a flash of unstyled text is better than not seeing the site at all
Joni Korpi has a nice article on loading fonts before the rest of the page.
http://jonikorpi.com/a-smoother-page-load/
He also uses a loading.gif to alleviate the delay so users won't get frustrated.
Maybe something like this:
$("body").html("<img src='ajax-loader.gif' />");
Then when the page loads, replace body's content with the actual content and hopefully, fully rendered fonts, you may have to play around with this though...