Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

路由预加载--预先加载延迟模块 #4

Open
deepthan opened this issue Dec 19, 2017 · 0 comments
Open

路由预加载--预先加载延迟模块 #4

deepthan opened this issue Dec 19, 2017 · 0 comments

Comments

@deepthan
Copy link
Owner

  • 使用懒加载才会存在预加载的概念
  • 预加载是自己加载完了再去加载其他模块
  • 注意,是自己加载完也就是闲时再去加载

预加载指定模块

参考了很多例子,虽然实现了预加载但却是在本模块内容没加载完就会去加载延迟模块,这样就等于没有配置懒加载,所以得进行一些优化。

1. 虽然配置了预加载但却在本模块没加载完就去加载延迟模块了(bad)

├─app.module.ts
├─app.routes.ts
├─shared
       └─service
           └─preview-load.ts

preview-load.ts

import { Observable } from 'rxjs/Rx';
import { PreloadingStrategy, Route } from '@angular/router';

export class PreloadModules implements PreloadingStrategy {
    preload(route: Route, load: Function): Observable<any> {
        return route.data && route.data.preload ? load() : Observable.of(null);
    }
}

app.module.ts

import { ROUTER_CONFIG } from './app.routes';
import { PreloadModules } from './share/service/preview-load';
...
@NgModule({
 imports: [
    RouterModule.forRoot(ROUTER_CONFIG, {preloadingStrategy:  PreloadModules} )
 ],
 providers: [
    PreloadModules
  ],

app.routes.ts

...

export const ROUTER_CONFIG: Routes = [
  ...
  {
    path: 'login',
    component: RoleLoginComponent
  },
  {
    path: 'lists',
    loadChildren: './tables/tables.module#TablesModule', 
    data: { preload: true } 
  }
];

实测:

  • 在250ms的时候页面没有渲染好并且没有加载延迟加载的table模块

image

  • 在2.55s的时候文件加载完成并开始渲染页面,这时候已经加载了table模块的js了,这就违背了预先加载延迟模块的初衷了。所以得治~

image

2. 闲时再加载延迟模块(good)

部分文件、结构和上面一样,只对preview-load.ts文件做一些更改

import { Observable } from 'rxjs/Rx';
import { PreloadingStrategy, Route } from '@angular/router';
import { Injectable, NgZone } from '@angular/core';

export function requestIdle(zone: NgZone) {
  const win: any = window;
  if (win.requestIdleCallback) {
    return (fn) => win.requestIdleCallback(fn);
  }
  return (fn) => zone.runOutsideAngular(() => win.setTimeout(fn, 10));
}

@Injectable()
export class PreloadModules implements PreloadingStrategy {

  constructor(
    private zone: NgZone
  ) { }

  preload(route: Route, fn: () => Observable<any>): Observable<any> {
    requestIdle(this.zone)(fn);
    return Observable.of(null);
  }

}

看结果

  • 在2.92s的时候页面渲染完成那一刻还是没有加载table模块

image

  • 在所有加载完之后开始加载table模块

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant