preloadFont()
此函数是 @remotion/preload
包的一部分。
此函数预加载字体,以便在挂载 <Img>
标签时,可以立即显示。
虽然预加载对于渲染并非必需,但它可以帮助在 <Player />
和 Studio 中实现无缝播放。
preloadFont()
的替代方案是 prefetch()
API。查看 @remotion/preload
vs prefetch()
来决定哪个更适合您的用例。
用法
tsx
import {preloadFont } from "@remotion/preload";constunpreload =preloadFont ("https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmYUtfBxc4AMP6lbBP.woff2");// If you want to un-preload the font laterunpreload ();
tsx
import {preloadFont } from "@remotion/preload";constunpreload =preloadFont ("https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmYUtfBxc4AMP6lbBP.woff2");// If you want to un-preload the font laterunpreload ();
工作原理
一个 <link rel="preload" as="font">
标签会被添加到文档的 head 元素中。
处理重定向
如果字体 URL 重定向到另一个 URL,则预加载原始 URL 将无效。
如果您包含的 URL 是未知的,请使用 resolveRedirect()
来以编程方式获取遵循潜在重定向的最终 URL。
如果资源不支持 CORS,resolveRedirect()
将失败。如果资源重定向,并且不支持 CORS,则无法预加载该资产。
此代码片段尝试尽最大努力预加载字体。如果无法解析重定向,则尝试预加载原始 URL。
tsx
import {preloadFont ,resolveRedirect } from "@remotion/preload";// This code gets executed immediately once the page loadsleturlToLoad ="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 loadurlToLoad =resolved ;}).catch ((err ) => {// Was unable to resolve redirect e.g. due to no CORS supportconsole .log ("Could not resolve redirect",err );}).finally (() => {// In either case, we try to preload the original or resolved URLpreloadFont (urlToLoad );});// This code only executes once the component gets mountedconstMyComp :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 >;};
tsx
import {preloadFont ,resolveRedirect } from "@remotion/preload";// This code gets executed immediately once the page loadsleturlToLoad ="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 loadurlToLoad =resolved ;}).catch ((err ) => {// Was unable to resolve redirect e.g. due to no CORS supportconsole .log ("Could not resolve redirect",err );}).finally (() => {// In either case, we try to preload the original or resolved URLpreloadFont (urlToLoad );});// This code only executes once the component gets mountedconstMyComp :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 >;};