UNPKG

1.25 kBPlain TextView Raw
1import FontObserver from 'fontfaceobserver';
2
3export default {
4 get name(): string {
5 return 'ExpoFontLoader';
6 },
7
8 loadAsync(fontFamilyName: string, resource: string): Promise<void> {
9 const canInjectStyle = document.head && typeof document.head.appendChild === 'function';
10 if (!canInjectStyle) {
11 throw new Error('E_FONT_CREATION_FAILED : document element cannot support injecting fonts');
12 }
13
14 const style = _createWebStyle(fontFamilyName, resource);
15 document.head!.appendChild(style);
16 return new FontObserver(fontFamilyName).load();
17 },
18};
19
20function _createWebStyle(fontFamily: string, resource: string): HTMLStyleElement {
21 const fontStyle = `@font-face {
22 font-family: ${fontFamily};
23 src: url(${resource});
24 }`;
25
26 const styleElement = document.createElement('style');
27 styleElement.type = 'text/css';
28 // @ts-ignore: TypeScript does not define HTMLStyleElement::styleSheet. This is just for IE and
29 // possibly can be removed if it's unnecessary on IE 11.
30 if (styleElement.styleSheet) {
31 // @ts-ignore
32 styleElement.styleSheet.cssText = fontStyle;
33 } else {
34 const textNode = document.createTextNode(fontStyle);
35 styleElement.appendChild(textNode);
36 }
37 return styleElement;
38}