preloadFont()
此函数是 @remotion/preload 包的一部分。
🌐 This function is part of the @remotion/preload package.
此功能会预加载字体,以便当<Img>标签被挂载时,它可以立即显示。
🌐 This function preloads a font so that when an <Img> tag is mounted, it can display immediately.
虽然预加载对于渲染不是必要的,但它可以帮助在 <Player /> 和 Studio 中实现无缝播放。
🌐 While preload is not necessary for rendering, it can help with seamless playback in the <Player /> and in the Studio.
preloadFont() 的一个替代方案是 prefetch() API。请参阅 @remotion/preload vs prefetch() 来决定哪一个更适合你的使用场景。
🌐 An alternative to preloadFont() is the prefetch() API. See @remotion/preload vs prefetch() to decide which one is better for your usecase.
用法
🌐 Usage
import { preloadFont } from "@remotion/preload";
const unpreload = preloadFont (
"https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmYUtfBxc4AMP6lbBP.woff2"
);
// If you want to un-preload the font later
unpreload ();它是如何运作的
🌐 How it works
一个 <link rel="preload" as="font"> 标签被添加到文档的头部元素中。
🌐 A <link rel="preload" as="font"> tag gets added to the head element of the document.
处理重定向
🌐 Handle redirects
如果字体 URL 重定向到另一个 URL,预加载原始 URL 将无效。
🌐 If the font URL redirects to another URL, preloading the original URL does not work.
如果你包含的 URL 是未知的,请使用 resolveRedirect() 来通过编程方式获取可能重定向后的最终 URL。
🌐 If the URL you include is unknown, use resolveRedirect() to programmatically obtain the final URL following potential redirects.
如果资源不支持 CORS,resolveRedirect() 将会失败。如果资源发生重定向,并且不支持 CORS,则无法预加载该资源。
🌐 If the resource does not support CORS, resolveRedirect() will fail. If the resource redirects, and does not support CORS, you cannot preload the asset.
这段代码尝试以最佳努力的方式预加载字体。如果重定向无法解析,它会尝试预加载原始 URL。
🌐 This snippet tries to preload a font on a best-effort basis. If the redirect cannot be resolved, it tries to preload the original URL.
import { preloadFont , resolveRedirect } from "@remotion/preload";
// This code gets executed immediately once the page loads
let urlToLoad =
"https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmYUtfBxc4AMP6lbBP.woff2";
resolveRedirect (urlToLoad )
.then ((resolved ) => {
// Was able to resolve a redirect, setting this as the font to load
urlToLoad = resolved ;
})
.catch ((err ) => {
// Was unable to resolve redirect e.g. due to no CORS support
console .log ("Could not resolve redirect", err );
})
.finally (() => {
// In either case, we try to preload the original or resolved URL
preloadFont (urlToLoad );
});
// This code only executes once the component gets mounted
const MyComp : React .FC = () => {
// If the component did not mount immediately, this will be the resolved URL.
// If the component mounted immediately, this will be the original URL.
// In that case preloading is ineffective anyway.
return <div style ={{ fontFamily : "Roboto" }}></div >;
};另请参阅
🌐 See also