Joaquin Brandan
Joaquin Brandan

Reputation: 2823

Preloading fonts using angular CLI

EDIT: AFAIK This is not a duplicate of Webpack disable hashing of image name on output because:

  • webpack.config is no longer editable in current angularCli versions.

  • I want to keep the hash on the file names for cache busting.

I'm using Angular and I would like to preload my fonts, i tried using

  <link rel="preload" href="assets/someFont.woff2" as="font" type="font/woff2" crossorigin="anonymous">

However angular hashes my fonts during the build process, so my font will be copied to the root folder and renamed to look something like this.

myFont.e31fcf1885e371e19f57.woff2

and my @fontface reference will point to that font.

So in the end I'm actually loading the same font twice instead of preloading the font, since the browser sees different URLs

How can I preload the fonts and keep the hashing functionality (for cache-busting)?

Upvotes: 22

Views: 7006

Answers (3)

jcroll
jcroll

Reputation: 7165

Use an absolute path to your assets folder when defining the font, this will prevent hashing of the font file on deployment:

@font-face {
  font-family: 'Open Sans';
  font-style: normal;
  font-weight: 400;
  font-display: swap;
  src: local('Open Sans'), local('OpenSans'), url('/assets/fonts/open-sans.woff') format('woff');
}

Then add a hard link to the font file in your index.html:

    ...
    <link rel="preload" href="/assets/fonts/open-sans.woff" as="font" crossorigin>
  </head>

Upvotes: 9

servrox
servrox

Reputation: 239

To prevent hashing of font files in the asset folder, you have to include the assets in your angular.json like following:

"assets": [{
            "glob": "**/*",
            "input": "src/assets",
            "output": "assets"
          }]

instead of

"assets": ["src/assets"]

Upvotes: 0

Maksim Sentiabov
Maksim Sentiabov

Reputation: 1

I was helped by the following actions. Transfer fonts files to assets folder. In styles set absolute path to fonts.

@font-face {
    font-family: 'CoreSans';
    font-style: normal;
    src: url('/assets/fonts/CoreSans.woff') format('woff');
}

Upvotes: -1

Related Questions