Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to preload a font with with Webpack Encore and webfonts-loader?

My project is built on :

  • Symfony / Webpack Encore bundle
  • webfonts-loader

Running a Lighthouse audit, the first opportunity to improve performances is :

Consider using <link rel=preload> to prioritize fetching resources that are currently requested later in page load ...fonts/app.icons.e5d7e11....woff

How can I automatically insert Link tag with rel="preload" to this file ?

like image 499
Neko Avatar asked Jan 27 '20 19:01

Neko


2 Answers

If you can use the latest Webpack Encore, this is directly supported via webpack_encore.yaml, simply set preload:true under the webpack_encore: key. You can use the standard helper methods in this case.

Example:

{{ encore_entry_link_tags('my_entry_point') }}
{{ encore_entry_script_tags('my_entry_point') }}

Source: https://github.com/symfony/webpack-encore-bundle

However, if you have an older version of Encore, you will need to install web-link composer require symfony/web-link as suggested in another answer, and manually iterate the webpack files using the encore file helpers, instead of the typical encore tag helpers.

Example:

{% for file in encore_entry_css_files('my_entry_point') %}
     <link rel="stylesheet" href="{{ preload(asset(file), {as: 'style'}) }}">
{% endfor %}

{% for file in encore_entry_js_files('my_entry_point') %}
     <script src="{{ preload(asset(file), {as: 'script'}) }}"></script>
{% endfor %}
like image 171
colonelclick Avatar answered Sep 28 '22 02:09

colonelclick


The Encore bundle automatically installs and configures the Asset component (if using Symfony Flex), after which you can use asset() to retrieve the versioned fonts file.

Assuming that you configured Webpack Encore to generate files to public/build/:

// In base.html.twig <head>:
<link rel="preload" href="{{ asset('build/fonts/some-font.woff2') }}" as="font" crossOrigin="anonymous" />

This will result in the following tag being rendered:

<link rel="preload" href="/build/fonts/some-font.6f75f467.woff2" as="font" crossorigin="anonymous">

Internally, asset() uses the manifest.json that Webpack generates.

like image 26
Pieter van den Ham Avatar answered Sep 28 '22 04:09

Pieter van den Ham