microapp.ts 1.58 KB
/**
 * 微应用容器相关工具函数
 */

/**
 * 等待微应用容器就绪
 * 确保 #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.getElementById('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.getElementById('subapp-container');
  return !!container;
}

/**
 * 等待容器就绪并执行回调
 * @param callback 容器就绪后执行的回调函数
 * @param onTimeout 超时后执行的回调函数(可选)
 * @param maxRetries 最大重试次数
 */
export async function onMicroAppContainerReady(
  callback: () => void | Promise<void>,
  onTimeout?: () => void,
  maxRetries: number = 20
): Promise<void> {
  const isReady = await waitForMicroAppContainer(maxRetries);
  if (isReady) {
    await callback();
  } else if (onTimeout) {
    onTimeout();
  }
}