angular - 首次应用渲染后延迟模块预加载
问题描述
我目前正在开发单页应用程序。在主页上显示了几张卡片。这些卡可以启用或禁用。如果禁用,则仅显示卡的标题。如果启用,则会显示卡片的标题和内容(延迟加载)。默认情况下,所有卡片都会显示和禁用。根据用户的档案,加载页面时,某些卡片可能处于活动状态。
目前,我没有设置任何preloadingStrategy,因此,在加载页面时,只加载活动卡片的内容。
我尝试将 preloadingStrategy 设置为 preloadAllModules,它工作正常,但它减慢了应用程序的启动速度。实际上,由于所有模块同时加载,因此活动卡片的内容显得较慢。
=> 我想要的是: 1. 加载应用程序 2. 加载所有活动卡的内容 3. 预加载所有其他在启动时未显示的模块
=> 第一次渲染后某种延迟预加载
=> 你认为这可能吗?
提前感谢您的反馈
解决方案
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
});
推荐阅读
- google-cloud-platform - 如何将 Cloud SQL 产品数据库与另一个 Cloud SQL 暂存数据库同步?
- php - 合并两个子数组
- ruby-on-rails - 如何在 Rails 中获取 ApplicationRecord 模型的验证约束?
- flutter-dependencies - 任务 ':app:processDebugResources' 执行失败。飘飘然
- c - 使用 MPI Alltoallw 处理不同子阵列尺寸的 3D 阵列散射
- java - 将数据推送到 BigQuery 中的现有表
- c# - Openxml SDK CreateFromTemplate 示例
- webots - 精准转动机器人
- python - 如何在 AngularJS 网站上使用 Python 中的 Selenium 迭代和保存动态表中的信息
- ruby-on-rails - 如何获取当前的设计用户?