I'm using the google font API to retrieves all google fonts. I got all the fonts as a Object contains each font item like the following :
{
"family" : "Roboto",
"variants" : ["100", "100italic", "300", "300italic"],
...
},
{...}
Now I use the WebFonts Loader Package to load the fonts. But I want to check if the font is already loaded in the document (to avoid load the same font twice) : Using this function :
const isFontLoaded = (fontName) => {
const fontNameFormated = fontName.split(':')[0].replaceAll(' ', ' '); // Formatting any font name like Open Sans:100,300italic to Open Sans
return document.fonts.check('16px ' fontNameFormated);
};
The output was :
fonts.js:129 Uncaught DOMException: Failed to execute 'check' on 'FontFaceSet': Could
not resolve '16px M PLUS Rounded 1c' as a font.
What I noticed is that the error only appears when a font family has a name including a digit. Like M PLUS Rounded 1c, Exo 2 ...
Plus when I add the following regex .replaceAll(/[0-9]/g, '');
to remove all digits on each font family name, it work's correctly. But now the document.fonts.check
method return false (probably because the font name is invalid).
Test :
const fonts = ['Roboto', 'M PLUS Rounded c', 'M PLUS Rounded 1c', 'Exo 2'];
fonts.forEach((font) => {
console.log(font, document.fonts.check('16px ' font));
})
CodePudding user response:
You need to wrap your font name in quotes, which would be true if used for CSS too.
const fonts = ['Roboto', '"M PLUS Rounded c"', '"M PLUS Rounded 1c"', '"Exo 2"'];
fonts.forEach((font) => {
console.log(font, document.fonts.check('16px ' font));
})