Magento 2 loading google fonts using Web Font loader

475 views Asked by At

Below is the Web font loader code trying to add it to Magento 2?

WebFontConfig = { 
google: { 
    families: ['Montserrat:light,medium,regular,semi-bold,bold,italic,regular', 'IBM Plex Serif:light,extra-light,regular,semi-bold,bold,italic,medium-italic,regular', 'Muli:light,extra-light,regular,semi-bold,bold,italic,regular'] 
    }, 
    timeout: 2000 // Set the timeout to two seconds 
}; 
(function(d) { 
    var wf = d.createElement('script');
    s = d.scripts[0]; 
    wf.src = 'https://ajax.googleapis.com/ajax/libs/webfont/1.6.26/webfont.js'; 
    wf.async = true; s.parentNode.insertBefore(wf, s); 
})(document);

What would be the best approach to do this? Tried adding it in "default_head_blocks.xml" doesnt work?

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <head>
        <script src="js/googleFonts.js"></script>
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no"/>
    </head>
</page>
1

There are 1 answers

0
KamS On

Try to add this code just before closing body tag

<script>
  WebFontConfig = {
    google: { families: ['Montserrat:light,medium,regular,semi-bold,bold,italic', 'IBM Plex Serif:light,extra-light,regular,semi-bold,bold,italic,medium-italic', 'Muli:light,extra-light,regular,semi-bold,bold,italic']  }
  };
  (function() {
    var wf = document.createElement('script');
    wf.src = 'https://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js';
    wf.type = 'text/javascript';
    wf.async = true;
    var s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(wf, s);
  })(); 
</script>

Moreover, make sure if you need all those fonts with all variants (like light,extra-light, bold, semi-bold) in your project.

If you really want to improve loading time for your website, please consider limiting fonts and its variants to a minimum.