1 | import FontObserver from 'fontfaceobserver';
|
2 |
|
3 | export 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 |
|
20 | function _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 |
|
29 |
|
30 | if (styleElement.styleSheet) {
|
31 |
|
32 | styleElement.styleSheet.cssText = fontStyle;
|
33 | } else {
|
34 | const textNode = document.createTextNode(fontStyle);
|
35 | styleElement.appendChild(textNode);
|
36 | }
|
37 | return styleElement;
|
38 | }
|