Andrey Drozdov
Andrey Drozdov

Reputation: 591

HTML pre-load font and use it in css

I'm aware that all of you know, if we do this in our .css file:

@font-face {
        font-family: "Akrobat-Regular";
        src: url('/assets/Akrobat-Regular.otf') format("truetype");
      }
      body {
        color: #1c1c1c;
        font-family: "Akrobat-Regular" !important;
      }

Browser will do additional request to download font, and as a result there will be a short amount of time when default font will be used and then they will be substituted with new downloaded.

I found this way to preload font, but really don't know how top use downloaded font without additional request (don't worry, ti as slim syntax):

    link rel='preload' href='/assets/Akrobat-Regular.otf' as='font' type='font/otf'

    = stylesheet_link_tag 'application'

    css:
      @font-face {
        font-family: "Akrobat-Regular";
        src: url('/assets/Akrobat-Regular.otf') format("truetype");
      }
      body {
        color: #1c1c1c;
        font-family: "Akrobat-Regular" !important;
      }

Upvotes: 3

Views: 8785

Answers (1)

bhansa
bhansa

Reputation: 7534

You can use the pre loaded fonts without creating a font-face as well.

<link rel="preload" href="your_font_file" as="font" type="font/woff" crossorigin="anonymous">

Just mention the font family to use it:

font-family: "your_font";

This way you don't need to put an additional request, as you have already loaded the font in your document.

Check the below example:

div.rob {
  font-family: "Roboto";
  font-size: 20px;
}
<link rel="preload" href="https://github.com/FontFaceKit/roboto/blob/gh-pages/fonts/Regular/Roboto-Regular.woff" as="font" type="font/woff" crossorigin="anonymous">

<div class="rob">
  Hola in roboto
</div>

<div>
  Normal font
</div>

Upvotes: 5

Related Questions