A component lazy loading feature for Angular6.0 implementation

One problem we often encounter is that when we use a third-party control library, we only use one or a few of the components, resulting in a lot of useless stuff, resulting in a large volume. Or home use component is more, the home page loading speed is slow, at this time, we may need to load the user a visual component within the scope of use, as users browse the drop-down, we’ll load these components, incremental load, progressive experience, this time you may use this tool to implement function. Or some unimportant areas of a page, such as third-party ads or unimportant elements, can be lazy loading lazy rendering to reduce the user’s first screen wait time. Everything happens without the user noticing. Greatly increase user experience, especially in large projects, optimization necessary!

Since 1.0.1, we have simplified the configuration process. We do not need to configure the route name selector.

version

  • v1.0.2
  • v1.0.1
  • v1.0.0

The installation

yarn add iwe7-lazy-load
Copy the code

use

import { Iwe7LazyLoadModule, LazyComponentsInterface } from 'iwe7-lazy-load';
// The lazy component used
let lazyComponentsModule: LazyComponentsInterface[] = [
  {
    // Selector of the component
    path: 'lazy-test'.// The relative address of the component
    loadChildren: './lazy-test/lazy-test.module#LazyTestModule'}];@NgModule({
  imports: [Iwe7LazyLoadModule.forRoot(lazyComponentsModule)],
  // Note these additions
  schemas: [CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA]
})
export class AppModule {}
Copy the code
<div #ele>
  <lazy-test></lazy-test>
</div>
Copy the code
import { LazyLoaderService } from 'iwe7-lazy-load';

@ViewChild('ele') ele: ElementRef;
constructor(
  public lazyLoader: LazyLoaderService,
  public view: ViewContainerRef
) {}

ngOnInit() {
  // Start rendering lazy components
  this.lazyLoader.init(this.ele.nativeElement, this.view);
}
Copy the code

Define lazy loading component Demo

import { LazyComponentModuleBase } from 'iwe7-lazy-load';
@Component({
  selector: 'lazy-test',
  template: ` i am a lazy`
})
export class LazyTestComponent {}

@NgModule({
  declarations: [LazyTestComponent],
  entryComponents: [
    LazyTestComponent
  ]
})
export class LazyTestModule extends LazyComponentModuleBase {
  getComponentByName(key: string): Type<any> {
    returnLazyTestComponent; }}Copy the code

summary

Hope to help you