Neko
Neko

Reputation: 181

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

My project is built on :

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 ?

Upvotes: 10

Views: 3179

Answers (3)

colonelclick
colonelclick

Reputation: 2215

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 %}

Upvotes: 5

Pieter van den Ham
Pieter van den Ham

Reputation: 4494

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.

Upvotes: 2

user9093397
user9093397

Reputation:

You can use the preload twig function from the symfony/web-link package. First, install the package with

composer require symfony/web-link

then, in your code, for example:

<link rel="stylesheet" href="{{ preload('/app.css', { as: 'style' }) }}">

Source: https://symfony.com/doc/current/web_link.html

Upvotes: 0

Related Questions