Reputation: 15
To fix a bug that only occurs in Firefox, I need to use the loaded
Promise of a FontFace
. I currently use the following code for that:
if (document.fonts) {
for (var fontFace of document.fonts.values()) {
if (fontFace['family'] == fontFamily) {
fontFace.loaded.then(doStuff);
}
}
} else {
doStuff();
}
This works and only targets the browsers that support the font loading API. But because of the for .. of
, Internet Explorer logs an error and stops the JS execution. Putting the code in a try .. catch
block doesn't work, ignoring the error via window.onerror
would probably work, but is quite hacky.
Is there a way to iterate over document.fonts.values
that is also supported by IE or do you know a better way to use the loaded
Promise in browsers that support it?
Upvotes: 0
Views: 214
Reputation: 161457
I'd recommend
const fontFace = Array.from(document.fonts).find(face => face.family === fontFamily);
if (fontFace) {
fontFace.loaded.then(doStuff);
}
Array.from
creates an array from an iterable, and then you can use the normal Array.prototype.some
to check for matches.
You could then simplify your whole check to
const fontFace = document.fonts &&
Array.from(document.fonts).find(face => face.family === fontFamily);
if (fontFace) fontFace.loaded.then(doStuff);
else doStuff();
assuming you want to run doStuff
if not of the font faces match either.
Upvotes: 2
Reputation: 15
I solved the problem with the following code:
if (document.fonts) {
var iter = document.fonts.values();
do {
var item = iter.next();
var fontFace = item.value;
if (fontFace && fontFace['family'] == fontFamilyStr) {
fontFace.loaded.then(doStuff);
}
} while (!item.done);
} else {
doStuff();
}
IE doesn't log an error anymore and the code works in Firefox / Chrome.
Upvotes: 1
Reputation: 9746
Unfortunately, you can't use for-of
iteration in your code, when it is supposed to run in an unsupported browser. The thing is that error occurs at the moment of parsing code before your condition will be executed and checked.
If you really want to use for-of, you will need to create a special JS-bundle for modern browsers or process your code with Babel to convert your code to es5-compatible.
Upvotes: 1