2

I am using these icons fonts of Google: https://material.io/icons/

I am developing a web extension and some web pages like Github is blocking my icons, I am trying to check with vanilla js if the font is available or not, the problem here is that I don't know when I need to confirm if the font was loaded or not.

I am using a setTimeOut but I really hate this method.

My code:

function confirmFont(view) {

     setTimeout(function(){
         if(!document.fonts.check("12px Material-Icons")) {
             .....
         }
     }, 2000);

 }

I tried with document ready and window load but this is not working I need to be more specific.

2 Answers2

3

If you already use document.fonts, why not use the Events that come with that interface? As a loadingdone event is fired whenever a font face set has finished loading, you could actually use an event listener to check your fonts. Below is a working example:

!function() {
    // Setting up listener for font checking
    var font = "1rem 'Material Icons'";
    document.fonts.addEventListener('loadingdone', function(event) {
        console.log(`Checking ${font}: ${ document.fonts.check(font)}`);
    })

    // Loading font
    var link = document.createElement('link'),
        head = document.getElementsByTagName('head')[0];

    link.addEventListener('load', function() {
        console.log('Font loaded');
    })

    link.type = 'text/css';
    link.rel = 'stylesheet';
    link.href = 'https://fonts.googleapis.com/icon?family=Material+Icons';
    head.appendChild(link);
}()
<i class="material-icons md-48">face</i>
dferenc
  • 7,918
  • 12
  • 41
  • 49
1

I have solved this in the following way:

document.fonts.ready.then(function () {
    if(!document.fonts.check("12px Material-Icons")) {
        ...
    }
});