首页 > 解决方案 > 首次应用渲染后延迟模块预加载

问题描述

我目前正在开发单页应用程序。在主页上显示了几张卡片。这些卡可以启用或禁用。如果禁用,则仅显示卡的标题。如果启用,则会显示卡片的标题和内容(延迟加载)。默认情况下,所有卡片都会显示和禁用。根据用户的档案,加载页面时,某些卡片可能处于活动状态。

目前,我没有设置任何preloadingStrategy,因此,在加载页面时,只加载活动卡片的内容。

我尝试将 preloadingStrategy 设置为 preloadAllModules,它工作正常,但它减慢了应用程序的启动速度。实际上,由于所有模块同时加载,因此活动卡片的内容显得较慢。

=> 我想要的是: 1. 加载应用程序 2. 加载所有活动卡的内容 3. 预加载所有其他在启动时未显示的模块

=> 第一次渲染后某种延迟预加载

=> 你认为这可能吗?

提前感谢您的反馈

标签: angular

解决方案


I believe it's possible, you have to make a custom preload strategy:

You can update your root router configuration like this:

@Injectable({
  providedIn: 'root'
})
export class CustomPreload implements PreloadingStrategy {
  preload(route: Route, load: (): Observable<any>): Observable<any> {
    // you implement this function somewhere, somehow
    if (isActiveCardRoute(route)) {
      // this will make it load immediately
      return load();
    } else {
      /* 
       * this will load the remaining modules after 5 seconds. You can possibly make a more
       * 'complex' logic to have it load sequentially or in bigger intervals to make sure
       * the app doesn't lag when loading
      */
      return timer(5000).pipe(
        switchMap(() => load())
      )
    }
  }
}

If somehow you need to find out before this, if a card is active or not by loading the api/logging in. You need to add this logic to the APP_INITIALIZER, or I guess you can add it to the CustomPreload as well, by injecting the appropriate services.

This CustomPreload, you can add to your RouterConfig:

RouterModule.forRoot(AppRoutes, {
  preloadingStrategy: CustomPreload
});

推荐阅读