microapp.ts
1.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/**
* 微应用容器相关工具函数
*/
/**
* 等待微应用容器就绪
* 确保 #subapp-container 元素已经挂载到 DOM 中
* @param maxRetries 最大重试次数,默认 20 次
* @param retryInterval 重试间隔(毫秒),默认 50ms
* @returns 返回容器是否就绪
*/
export async function waitForMicroAppContainer(
maxRetries: number = 20,
retryInterval: number = 50
): Promise<boolean> {
for (let i = 0; i < maxRetries; i++) {
const container = document.querySelector("#subapp-container");
if (container) {
console.log(`[微应用工具] 容器已就绪 (尝试 ${i + 1}/${maxRetries})`);
return true;
}
// 等待指定时间后重试
await new Promise(resolve => setTimeout(resolve, retryInterval));
}
console.error(`[微应用工具] 等待容器超时 (${maxRetries * retryInterval}ms)`);
return false;
}
/**
* 检查容器是否已存在
* @returns 容器是否存在
*/
export function isMicroAppContainerReady(): boolean {
const container = document.querySelector("#subapp-container");
return !!container;
}
/**
* 等待容器就绪并执行回调
* @param callback 容器就绪后执行的回调函数
* @param onTimeout 超时后执行的回调函数(可选)
* @param maxRetries 最大重试次数
*/
export async function onMicroAppContainerReady(
callback: () => Promise<void> | void,
onTimeout?: () => void,
maxRetries: number = 20
): Promise<void> {
const isReady = await waitForMicroAppContainer(maxRetries);
if (isReady) {
await callback();
} else if (onTimeout) {
onTimeout();
}
}