This time I will bring you lazy loading in angular6.0. What are the precautions for lazy loading in angular6.0? The following is a practical case, let’s take a look.
We often encounter such a problem. When we use a third-party control library, we only use one or a few of its components, which will bring along a lot of useless things, causing the volume. Too bloated. Or the home page uses many components and the loading speed of the home page is slow. At this time, we may need to load the components used within the user's visual range. As the user scrolls down, we will load these components again and load them progressively. Progressive experience, at this time you may use the functions implemented by this tool. Or some unimportant areas of a page, such as third-party advertisements or unimportant elements, can use lazy loading and lazy rendering to reduce the user's first screen waiting time. Everything happens without the user knowing it. Greatly improves user experience, especially for medium and large projects, optimization is a must!
Project addressgithub
Installation
yarn add iwe7-lazy-load
Use
import { Iwe7LazyLoadModule, LazyComponentsInterface } from 'iwe7-lazy-load'; // 用到的懒加载组件 let lazyComponentsModule: LazyComponentsInterface[] = [ { // 组件的selector path: 'lazy-test', // 组件的相对地址 loadChildren: './lazy-test/lazy-test.module#LazyTestModule' } ]; @NgModule({ imports: [Iwe7LazyLoadModule.forRoot(lazyComponentsModule)], // 注意加上这些 schemas: [CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA] }) export class AppModule {}
import { LazyLoaderService } from 'iwe7-lazy-load'; @ViewChild('ele') ele: ElementRef; constructor( public lazyLoader: LazyLoaderService, public view: ViewContainerRef ) {} ngOnInit() { // 开始渲染懒组件 this.lazyLoader.init(this.ele.nativeElement, this.view); }
Define lazy loading component demo
import { LazyComponentModuleBase } from 'iwe7-lazy-load'; @Component({ selector: 'lazy-test', template: ` i am a lazy` }) export class LazyTestComponent {} @NgModule({ imports: [ RouterModule.forChild([{ path: '', component: LazyTestComponent }]) ], declarations: [LazyTestComponent] }) export class LazyTestModule extends LazyComponentModuleBase { getComponentByName(key: string): Type{ return LazyTestComponent; } }
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
angular print page specified function
##Detailed explanation of render case in React
The above is the detailed content of Angular6.0 makes lazy loading. For more information, please follow other related articles on the PHP Chinese website!