csswordpressfont-facepreloadlighthouse

Do you need to pre-load fonts in the <head> and declare them in CSS as a font-face?


My question comes from trying to optimize for lighthouse test's preloading key assets.

I've placed the fonts flagged by lighthouse report in Chrome browser into a link in my head file.

[header.php]

<link rel=”preload” href=”/wp-content/themes/mytheme/assets/font/Roboto/Roboto-Regular.ttf” as=”font” crossorigin=”anonymous”>

Do I still need to include it in my style.css file and declare the font-face?

[style.css]

@font-face {
  font-family: "Roboto";
  src: url("/wp-content/themes/mytheme/assets/font/Roboto/Roboto-Regular.ttf") format("truetype"); }

I'm asking because despite adding the preload link in my header, Lighthouse report still shows that my file is not preloading.

Thanks for your help all.


Solution

  • Both declaration don't have the same goal.

    The preload value of the element's rel attribute lets you declare fetch requests in the HTML's , specifying resources that your page will need very soon, which you want to start loading early in the page lifecycle, before browsers' main rendering machinery kicks in.

    If you add preload by itself, your font won't be taken into account. You have to specify the action too.

    <link rel="preload" href="style.css" as="style"> <!--preload-->
    <link rel="stylesheet" href="style.css"> <!--action-->
    

    Here we preload our CSS and JavaScript files so they will be available as soon as they are required for the rendering of the page later on.

    Like Graham said in the comment, preload can only be efficient if it is specified before any font related actions like the <link> tag (loading font via html) or the css file itself.

    Additionally, your request is dependent to style.css. loading your font in the html could greatly improve performance. Either by inlining it in a <style> tag or by loading through the <link> tag.

    With the recents improvements to font servicing using CDNs, loading a font from a locally saved version as become inefficient. The local version should be used as a fallback. I would recommend you take a look at Google Fonts.

    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;700&display=swap" rel="stylesheet">
    

    On a side note .ttf shouldn't be used, it's not optimised. @ https://stackoverflow.com/a/11002874/3645650 consider using .woff and .woff2 instead.

    (Run lighthouse with your browser set to incognito mode, to get actual reliable information).