UNPKG

@needle-tools/engine

Version:

Needle Engine is a web-based runtime for 3D apps. It runs on your machine for development with great integrations into editors like Unity or Blender - and can be deployed onto any device! It is flexible, extensible and networking and XR are built-in.

47 lines (41 loc) 1.94 kB
import { materialSymbolsFontUrl,robotoFlexFontUrl } from "./font-urls.js"; declare type LoadFontOptions = { element?: HTMLElement | DocumentFragment, loadedCallback?: () => void, } export function loadFont(url: string, opts?: LoadFontOptions) { const element = opts?.element || document.head; // Workaround for font loading not being supported in ShadowDOM: // Add font import to document header. // Note that this is slower than it could be, ideally the font would be prefetched, // but for that it needs to be in the actual document and not added by JS. const elements = Array.from(element.querySelectorAll(`link[href*='${url}']`)); if (elements.length <= 0) { const fontLink = document.createElement("link"); fontLink.href = url; // Load fonts without blocking render: use rel="preload" with onload swap // to stylesheet. This avoids the ~200ms render-blocking delay per font. fontLink.rel = "preload"; fontLink.as = "style"; // crossorigin must match the HTML <link> attribute (set by asap.js) so the browser // can reuse the cached CORS response instead of making a separate non-CORS request fontLink.crossOrigin = ""; fontLink.onload = () => { fontLink.rel = "stylesheet"; }; element.appendChild(fontLink); elements.push(fontLink); } if (opts?.loadedCallback) { for (let i = 0; i < elements.length; i++) { if (opts?.loadedCallback) { const fontLink = elements[i] as HTMLLinkElement; fontLink.addEventListener("load", opts.loadedCallback); } } } } /** Ensure the fonts that needle engine uses are loaded */ export function ensureFonts() { loadFont(robotoFlexFontUrl); } export { materialSymbolsFontUrl as iconFontUrl }; // const fontUrl = "./include/fonts/MaterialSymbolsOutlined.css"; // for offline support