Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML pre-load font and use it in css

Tags:

html

css

fonts

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;
      }
like image 290
Andrey Drozdov Avatar asked Nov 24 '25 22:11

Andrey Drozdov


1 Answers

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>
like image 103
bhansa Avatar answered Nov 27 '25 13:11

bhansa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!