3

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;
      }
Andrey Drozdov
  • 571
  • 1
  • 5
  • 22

1 Answers1

5

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>
bhansa
  • 7,282
  • 3
  • 30
  • 55
  • ` must have a valid 'as' value`, but font still is not loading :( You have the same warning – Andrey Drozdov Nov 14 '17 at 20:24
  • The font loads in the example perfectly, I don't see any error. I am using chrome btw. – bhansa Nov 14 '17 at 20:26
  • I can't make it to work, in my example, when I `href='/assets/Akrobat-Regular.otf'` trying to get this font I receive status 200 (it's downloaded). But when I do `body { font-family: ''Akrobat-Regular.otf" }` font is not changing, even if I do this in `.css` or in `` tag – Andrey Drozdov Nov 14 '17 at 20:35
  • omit the `.otf` in font-family. Just use the name. – bhansa Nov 14 '17 at 20:36