I have a custom font in my theme already added through the "web/css/source/_typography.less".

& when (@media-common = true) {
    @family-name: @font-family-name__base,
    @font-path: '@{baseDir}fonts/poppins/light/Poppins-Light',
    @font-weight: 300,
    @font-style: normal

I am wondering how I can add a "preload" instruction? The problem is because due less the files will be preprocessed and generated. so I can not add a hardocded path in the "head" section of my site. The path will change each time I change the css / less files on the site i.e. the "version1612984603" will change when I flush cache or recompile the less files.

Example dynamic generated link by magento for that font file


Example preload instruction

    <link rel="preload" as="font" href="/static/version1612984603/frontend/<vendor>/<theme>/de_DE/fonts/poppins/light/Poppins-Light.woff">

So how can I do this?

Remark: I have seen that the <font>feature (see custom fonts) has been added in magento 2.3.x but I can not update my installation from 2.2 to 2.3 due the incompatibiity of some extensions.


1 Answer 1


You can do this by adding phtml file in head section

Step 1. Create default_head_blocks.xml file on path app\design\frontend<Vendor Name><theme name>\Magento_Theme\layout and add below code

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
        <referenceBlock name="head.additional">
            <block class="Magento\Framework\View\Element\Template" name="preload.custom.font" template="Magento_Theme::html/preload_fonts.phtml"/>

Step 2. Create new preload_fonts.phtml file on path app\design\frontend<Vendor Name><theme name>\Magento_Theme\templates\html

<link rel="preload" as="font" href="<?= $block->getViewFileUrl('fonts/poppins/light/Poppins-Light.woff2') ?>" type="font/woff2" crossorigin="anonymous">
  • After following this answer got below error: Element 'referenceBlock': This element is not expected. Expected is one of ( title, css, link, meta, script, remove, attribute, font ). Commented Aug 22, 2021 at 10:58
  • The head.additional node in the XML needs to go in between the <body> section (this is unintuitive), otherwise you will the error described above.
    – jaybong
    Commented May 24, 2022 at 12:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.