Preloading dynamically generated font-files inserted by Angular CLI

Viewed 652

I am beginning to adopt the <link rel="preload"> strategy for some of my fonts and by using the Lighthouse auditing tool, I have been able to find some good candidates.

Lighthouse recommends me 5, 3 of which are static and so are easy to preload. They take the form of:

<link rel="preload" href="/fonts/my-font.woff" as="font" type="font/woff">

The other 2 are generated dynamically by Angular and are inserted into my HTML at runtime. The issue with these fonts is that they take the name of my-font.sr7er987f.woff and I suspect this value will be different every time I build and deploy my app.

I was curious if there were a way to set a dynamic href attribute on my <link> that could grab these fonts? Something like <link rel="preload" href="fonts/my-font.*.woff".

Thanks

1 Answers

I faced the same dilemma and came up with a simple bash script to use right before deployment.

#!/bin/bash
for filename in ./path/*.ttf; do
  [ -e "$filename" ] || continue
  one=${filename#*./path/}
  two=${one%.*.ttf}
  three=${two%-*}
  salt=${one#*.}
  salt=${salt%.*}

  printf "Font:\n"
  printf 'assets/fonts/'"$three"'/'"$two"'.ttf\n'
  printf "was replaced with:\n"
  printf "$three"'.'"$salt"'.ttf\n'

  sed -i -e 's/assets\/fonts\/'"$three"'\/'"$two"'.ttf/'"$two"'.'"$salt"'.ttf/g' ./path/index.html
  printf "===SUCCESS===\n"

done

Not an elegant solution, but it gets the job done, replacing:

<link rel="preload" href="assets/fonts/Raleway/Raleway-Regular.ttf" as="font" crossorigin="anonymous">

with

<link rel="preload" href="Raleway-Regular.580d0778ad254335be45.ttf" as="font" crossorigin="anonymous">

So all you need to do is to configure paths and declare the fonts in index.html. With that said and done, I noticed that now these fonts get downloaded twice somehow, once as preload and again when requested by stylesheets (?). This might be just a caching problem or something, though.

Related