简体   繁体   English

Internet Explorer:忽略未知的ES6语法

[英]Internet Explorer: Ignore unknown ES6 syntax

To fix a bug that only occurs in Firefox, I need to use the loaded Promise of a FontFace . 要修复仅在Firefox中发生的错误,我需要使用已loadedFontFace Promise。 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. 这有效,并且仅针对支持字体加载API的浏览器。 But because of the for .. of , Internet Explorer logs an error and stops the JS execution. 但是由于for .. of ,Internet Explorer会记录错误并停止JS执行。 Putting the code in a try .. catch block doesn't work, ignoring the error via window.onerror would probably work, but is quite hacky. 将代码放在try .. catch块中是行不通的,通过window.onerror忽略错误可能会起作用,但是很hack。

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? 有没有一种方法可以遍历IE也支持的document.fonts.values ,或者您知道在支持它的浏览器中使用loaded Promise的更好方法吗?

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. Array.from从可迭代Array.from创建一个数组,然后可以使用常规Array.prototype.some检查匹配项。

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. 假设您要运行doStuff如果两个字体都不匹配)。

Unfortunately, you can't use for-of iteration in your code, when it is supposed to run in an unsupported browser. 不幸的是,当代码应在不受支持的浏览器中运行时,您将无法在代码中使用for-of迭代。 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. 如果您真的想使用for-of,则需要为现代浏览器创建一个特殊的JS捆绑包,或者使用Babel处理代码以将代码转换为与es5兼容。

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. IE不再记录错误,该代码可在Firefox / Chrome中运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM