Skip to content

Commit 9125119

Browse files
authored
feat(h5): 支持 preloadAssets (#19672)
* feat(h5): preload image and font assets * fix(h5): release settled preloads and isolate Harmony fallback * fix(h5): reject unsupported resource preloads
1 parent 056ffb9 commit 9125119

9 files changed

Lines changed: 225 additions & 9 deletions

File tree

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import Taro from '@tarojs/api'
2+
3+
import { loadHarmonyApi } from '../helpers/loadHarmonyApi'
4+
5+
afterEach(() => jest.restoreAllMocks())
6+
7+
it('keeps the Harmony Hybrid preloadAssets placeholder at the public entry', async () => {
8+
jest.replaceProperty(process.env, 'NODE_ENV', 'production')
9+
jest.spyOn(console, 'warn').mockImplementation(() => {})
10+
const appendChild = jest.spyOn(document.head, 'appendChild')
11+
const unsupported = jest.fn()
12+
const success = jest.fn()
13+
const fail = jest.fn()
14+
const preloadAssets = await loadHarmonyApi('preloadAssets')
15+
const options = { data: [{ type: 'image' as const, src: '/hero.png' }], success, fail }
16+
17+
Taro.eventCenter.on('__taroNotSupport', unsupported)
18+
try {
19+
const result = preloadAssets(options)
20+
expect(appendChild).not.toHaveBeenCalled()
21+
await expect(result).resolves.toEqual({ errMsg: '暂时不支持 API' })
22+
expect(unsupported).toHaveBeenCalledWith({
23+
name: 'preloadAssets', args: [options], type: 'method', category: 'temporarily',
24+
})
25+
expect(success).toHaveBeenCalledTimes(1)
26+
expect(fail).not.toHaveBeenCalled()
27+
} finally {
28+
Taro.eventCenter.off('__taroNotSupport', unsupported)
29+
}
30+
})
Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
import { preloadAssets } from '@tarojs/taro-h5'
2+
3+
describe('preloadAssets', () => {
4+
const links = () => Array.from(document.querySelectorAll<HTMLLinkElement>('link[rel="preload"]'))
5+
beforeEach(() => jest.spyOn(DOMTokenList.prototype, 'supports').mockReturnValue(true))
6+
afterEach(() => {
7+
links().forEach(link => link.remove())
8+
jest.restoreAllMocks()
9+
})
10+
11+
it('fails unsupported preloads without inserting or retaining a request', async () => {
12+
jest.spyOn(DOMTokenList.prototype, 'supports').mockReturnValue(false)
13+
const fail = jest.fn()
14+
const complete = jest.fn()
15+
const options = { data: [{ type: 'image' as const, src: '/unsupported.png' }], fail, complete }
16+
await preloadAssets(options)
17+
expect(fail).toHaveBeenCalledTimes(1)
18+
expect(complete).toHaveBeenCalledTimes(1)
19+
expect(links()).toHaveLength(0)
20+
jest.spyOn(DOMTokenList.prototype, 'supports').mockReturnValue(true)
21+
const retry = preloadAssets(options)
22+
expect(links()).toHaveLength(1)
23+
links()[0].dispatchEvent(new Event('load'))
24+
await retry
25+
})
26+
27+
it('preloads images and anonymous fonts and shares concurrent requests', async () => {
28+
const first = preloadAssets({ data: [{ type: 'image', src: '/hero.png' }, { type: 'font', src: '/font.woff2' }] })
29+
const second = preloadAssets({ data: [{ type: 'image', src: 'http://localhost/hero.png' }] })
30+
const [image, font] = links()
31+
expect(links()).toHaveLength(2)
32+
expect(image.as).toBe('image')
33+
expect(font.as).toBe('font')
34+
expect(font.crossOrigin).toBe('anonymous')
35+
36+
image.dispatchEvent(new Event('load'))
37+
font.dispatchEvent(new Event('load'))
38+
await expect(first).resolves.toMatchObject({ errMsg: 'preloadAssets:ok' })
39+
await expect(second).resolves.toMatchObject({ errMsg: 'preloadAssets:ok' })
40+
expect(links()).toHaveLength(0)
41+
})
42+
43+
it('cleans up consecutive batches and lets a completed URL be preloaded again', async () => {
44+
for (let batch = 0; batch < 4; batch++) {
45+
const data = Array.from({ length: 25 }, (_, index) => ({
46+
type: 'image' as const,
47+
src: `/batch-${batch}-${index}.png`,
48+
}))
49+
const request = preloadAssets({ data })
50+
expect(links()).toHaveLength(25)
51+
links().forEach(link => link.dispatchEvent(new Event('load')))
52+
await request
53+
expect(links()).toHaveLength(0)
54+
}
55+
56+
const repeat = preloadAssets({ data: [{ type: 'image', src: '/batch-0-0.png' }] })
57+
expect(links()).toHaveLength(1)
58+
links()[0].dispatchEvent(new Event('load'))
59+
await expect(repeat).resolves.toMatchObject({ errMsg: 'preloadAssets:ok' })
60+
expect(links()).toHaveLength(0)
61+
})
62+
63+
it('reports a failed asset and permits retry', async () => {
64+
const options = { data: [{ type: 'image' as const, src: '/retry.png' }] }
65+
const failed = preloadAssets(options)
66+
links()[0].dispatchEvent(new Event('error'))
67+
await expect(failed).rejects.toMatchObject({ errMsg: expect.stringContaining('retry.png') })
68+
expect(links()).toHaveLength(0)
69+
const retry = preloadAssets(options)
70+
links()[0].dispatchEvent(new Event('load'))
71+
await expect(retry).resolves.toMatchObject({ errMsg: 'preloadAssets:ok' })
72+
})
73+
74+
it('rejects malformed entries without scheduling a preload', async () => {
75+
await expect(preloadAssets({ data: [{ type: 'image', src: '' }] })).rejects.toMatchObject({
76+
errMsg: expect.stringContaining('preloadAssets:fail'),
77+
})
78+
expect(links()).toHaveLength(0)
79+
})
80+
81+
it('calls fail and complete once even when multiple assets fail', async () => {
82+
const fail = jest.fn()
83+
const complete = jest.fn()
84+
const success = jest.fn()
85+
const request = preloadAssets({
86+
data: [{ type: 'font', src: '/missing.woff2' }, { type: 'image', src: '/missing.png' }],
87+
fail,
88+
complete,
89+
success,
90+
})
91+
links().forEach(link => link.dispatchEvent(new Event('error')))
92+
const result = await request
93+
expect(fail).toHaveBeenCalledTimes(1)
94+
expect(fail).toHaveBeenCalledWith(result)
95+
expect(complete).toHaveBeenCalledTimes(1)
96+
expect(complete).toHaveBeenCalledWith(result)
97+
expect(success).not.toHaveBeenCalled()
98+
expect(links()).toHaveLength(0)
99+
})
100+
})
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import { isAbsolute, resolve } from 'node:path'
2+
import { runInNewContext } from 'node:vm'
3+
4+
import { rollup } from 'rollup'
5+
6+
import type Taro from '@tarojs/api'
7+
8+
/** Import a named API from the generated public entry through a real Rollup consumer. */
9+
export async function loadHarmonyApi<K extends keyof typeof Taro> (name: K): Promise<(typeof Taro)[K]> {
10+
const publicApi = resolve(__dirname, '../../../taro-platform-harmony-hybrid/dist/api/index.js')
11+
const consumer = '\0harmony-api-consumer'
12+
const bundle = await rollup({
13+
input: consumer,
14+
external: (id, importer) => !!importer && !id.startsWith('.') && !isAbsolute(id),
15+
treeshake: { moduleSideEffects: false },
16+
plugins: [{
17+
name: 'harmony-api-consumer',
18+
resolveId: id => id === consumer ? id : null,
19+
load: id => id === consumer ? `export { ${String(name)} } from ${JSON.stringify(publicApi)}` : null,
20+
}],
21+
})
22+
const exports: Pick<typeof Taro, K> = Object.create(null)
23+
try {
24+
const { output } = await bundle.generate({ format: 'cjs', exports: 'named', interop: 'auto' })
25+
runInNewContext(output[0].code, { exports, require, process, console, document, window })
26+
return exports[name]
27+
} finally {
28+
await bundle.close()
29+
}
30+
}

‎packages/taro-h5/src/api/base/performance.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,4 +5,4 @@ export const reportPerformance = /* @__PURE__ */ temporarilyNotSupport('reportPe
55
export const getPerformance = /* @__PURE__ */ temporarilyNotSupport('getPerformance')
66
export const preloadWebview = /* @__PURE__ */ temporarilyNotSupport('preloadWebview')
77
export const preloadSkylineView = /* @__PURE__ */ temporarilyNotSupport('preloadSkylineView')
8-
export const preloadAssets = /* @__PURE__ */ temporarilyNotSupport('preloadAssets')
8+
export * from './preloadAssets'
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
import Taro from '@tarojs/api'
2+
3+
import { shouldBeObject } from '../../utils'
4+
import { MethodHandler } from '../../utils/handler'
5+
6+
type Asset = Taro.preloadAssets.AssetsObject
7+
8+
const pendingRequests = new Map<string, Promise<void>>()
9+
10+
function preload ({ type, src }: Asset) {
11+
const url = new URL(src, document.baseURI).href
12+
const key = `${type}:${url}`
13+
const existing = pendingRequests.get(key)
14+
if (existing) return existing
15+
16+
const link = document.createElement('link')
17+
if (!link.relList?.supports?.('preload')) {
18+
return Promise.reject(new Error('preload is not supported by this browser'))
19+
}
20+
link.rel = 'preload'
21+
link.as = type
22+
link.href = url
23+
if (type === 'font') link.crossOrigin = 'anonymous'
24+
25+
const request = new Promise<void>((resolve, reject) => {
26+
link.onload = () => resolve()
27+
link.onerror = () => reject(new Error(`failed to preload ${type}: ${url}`))
28+
document.head.appendChild(link)
29+
}).finally(() => {
30+
pendingRequests.delete(key)
31+
link.onload = null
32+
link.onerror = null
33+
link.remove()
34+
})
35+
pendingRequests.set(key, request)
36+
return request
37+
}
38+
39+
export const preloadAssets: typeof Taro.preloadAssets = async options => {
40+
const name = 'preloadAssets'
41+
const validation = shouldBeObject(options)
42+
if (!validation.flag) return new MethodHandler({ name }).fail({ errMsg: validation.msg })
43+
44+
const { data, success, fail, complete } = options
45+
const handler = new MethodHandler({ name, success, fail, complete })
46+
if (!Array.isArray(data) || !Array.from(data).every(asset => asset &&
47+
(asset.type === 'image' || asset.type === 'font') && typeof asset.src === 'string' && asset.src.trim())) {
48+
return handler.fail({ errMsg: 'data must be an array of image or font sources' })
49+
}
50+
51+
try {
52+
await Promise.all(data.map(async asset => preload(asset)))
53+
} catch (error) {
54+
return handler.fail({ errMsg: error instanceof Error ? error.message : String(error) })
55+
}
56+
return handler.success()
57+
}

‎packages/taro-platform-harmony-hybrid/src/api/apis/base/index.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ export const env = {
2222
export * from './debug/index'
2323
export * from './getAppAuthorizeSetting'
2424
export * from './getSystemSetting'
25+
export { preloadAssets } from './performance'
2526
export * from './system'
2627
export * from './update'
2728
export * from './weapp/life-cycle'

‎packages/taro-platform-harmony-hybrid/src/api/apis/base/performance.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import Taro from '@tarojs/taro'
22

3+
import { temporarilyNotSupport } from '../utils'
4+
35
/**
46
* 程序测速上报
57
*
@@ -26,7 +28,7 @@ export { preloadSkylineView } from '@tarojs/taro-h5'
2628
*
2729
* @canNotUse preloadAssets
2830
*/
29-
export { preloadAssets } from '@tarojs/taro-h5'
31+
export const preloadAssets = /* @__PURE__ */ temporarilyNotSupport('preloadAssets')
3032

3133
/**
3234
* 程序测速上报

‎packages/taro-platform-harmony-hybrid/src/api/apis/comments.ts‎

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1218,12 +1218,6 @@
12181218
* @canNotUse pluginLogin
12191219
*/
12201220

1221-
/**
1222-
* 为视图层预加载媒体资源文件
1223-
*
1224-
* @canNotUse preloadAssets
1225-
*/
1226-
12271221
/**
12281222
* 预加载下个页面所需要的 Skyline 运行环境
12291223
*

‎packages/taro/types/api/base/performance.d.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -233,7 +233,9 @@ declare module '../../index' {
233233
preloadSkylineView(option: preloadSkylineView.Option): Promise<TaroGeneral.CallbackResult>
234234

235235
/** 为视图层预加载媒体资源文件, 目前支持:font,image
236-
* @supported weapp
236+
* H5 字体预加载采用匿名跨域请求。使用字体时仍需通过 CSS 声明字体。
237+
* H5 会复用进行中的请求,并在完成后移除预加载节点。之后再次调用会交由浏览器处理缓存。
238+
* @supported weapp, h5
237239
* @see https://developers.weixin.qq.com/miniprogram/dev/api/base/performance/wx.preloadAssets.html
238240
*/
239241
preloadAssets(option: preloadAssets.Option): Promise<TaroGeneral.CallbackResult>

0 commit comments

Comments
 (0)