Skip to content
On this page

preloadAssets

preloadAssets 可以用来预加载图片、字体资源

  • 图片资源通过 Image 构造函数加载
  • 字体资源通过 FontFace 构造函数加载并会被添加进 window.document.fonts

代码演示

ts
import preloadAssets from 'ufuse/src/utils/preloadAssets'

interface ImageModule {
  default: string
}

const ready = preloadAssets({
  images: [
    ...Object.entries(
      import.meta.glob(
        [
          '@/assets/images/menus/**/*',
          '@/assets/images/modules/**/*',
        ],
        { eager: true },
      ),
    )
      .map(([, module]) => (module as ImageModule).default),
  ],
  fonts: [
    ['FontA', '/FontA.ttf'],
  ],
})

ready.then(() => {
  // do something
})

API

ts
export interface preloadAssetsOptions {
  /**
   * 需要预加载的图片资源路径,应该提供一个没有别名(如 '@')的路径
   * @example ['/images/1.png']
   */
  images?: string[]
  /**
   * 需要预加载的字体资源,且会添加进 document.fonts
   * @example [['FontName', '/myFont.ttf']]
   */
  fonts?: [family: string, path: string, descriptors?: FontFaceDescriptors][]
}

贡献者

cuijin
xieyuhang