Skip to content

Instantly share code, notes, and snippets.

@HaNdTriX

HaNdTriX/useFont.js

Last active Jan 22, 2020
Embed
What would you like to do?
Concepts of simple font loader using react suspense.
function wrapPromise(promise) {
let status = "pending";
let result;
let suspender = promise.then(
r => {
status = "success";
result = r;
},
e => {
status = "error";
result = e;
}
);
return {
read() {
if (status === "pending") {
throw suspender;
} else if (status === "error") {
throw result;
} else if (status === "success") {
return result;
}
}
};
}
const loadFont = async fontFamily => {
const fontFace = new FontFace(fontFamily, `url(/api/font/${fontFamily}.ttf)`);
const loadedFontFace = await fontFace.load();
document.fonts.add(loadedFontFace);
};
const fontMap = new Map();
const useFont = fontFamily => {
if (!fontMap.has(fontFamily)) {
const loader = wrapPromise(loadFont(fontFamily));
fontMap.set(fontFamily, loader);
return loader.read();
}
return fontMap.get(fontFamily).read();
};
export default useFont;
@HaNdTriX

This comment has been minimized.

Copy link
Owner Author

@HaNdTriX HaNdTriX commented Jan 22, 2020

Usage:

const MyFontComponent = () => {
  useFont('Helvetica')
  return (
    <div>
      This string will only show up if font was loaded.
    </div>
  )
}

const App = () => (
  <React.Suspense fallback='loading font...'>
    <MyFontComponent />
  </React.Suspense>
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.