Ionic3懒加载实现
为什么使用懒加载?
在实际开发中,越复杂的功能就会占用越多资源,写越多的代码,那么打开App的时候就需要用更多的时间,因为是同时加载了所有的资源,切换也会使用更多的时间。那么为什么我需要什么才加载什么呢?
未使用懒加载之前:

image.png
可以在上图明显的看到三个选项卡布局的App把所有的资源都进行加载了,但是目前我只显示了home这个页面,另外两个页面我不需要立马加载的呀。
好了,问题的抛到这里,下面就进行怎么使用懒加载进行简单的说一下吧。
1.需要知道的几个概念,我不解释,angular学习中有。
组件
装饰器
模块
@IonicPage()装饰器。
具体操作如下:
a.为about,contact,home,tabs添加module,代码如下
import {NgModule} from "@angular/core";import {IonicPageModule} from "ionic-angular";import {AboutPage} from "./about";/**
* Created by 雷洪飞 on 2017/9/25.
* @function:
*/@NgModule({ imports: [
IonicPageModule.forChild(AboutPage)
], declarations: [
AboutPage
]
})export class AboutModule {
}b. 在tabs.ts中去掉对HomaPage,AboutPage,ContactPage的组件引用,更改为字符串,并且还需要在app.component.ts中,对rootPage:any = TabsPage也要设置为字符串.
import { Component } from '@angular/core';import {IonicPage} from "ionic-angular";
@IonicPage()
@Component({ templateUrl: 'tabs.html'})export class TabsPage { // 去掉组件引用,改为字符串
tab1Root = 'HomePage';
tab2Root = 'AboutPage';
tab3Root = 'ContactPage'; constructor() {
}
}c. 添加@IonicPage()特性,在组件中添加(HomePage,ContactPage,AboutPage,TabsPage).
import { Component } from '@angular/core';import {IonicPage, NavController} from 'ionic-angular';// 添加IonicPage特性@IonicPage()
@Component({ selector: 'page-contact', templateUrl: 'contact.html'})export class ContactPage { constructor(public navCtrl: NavController) {
}
}需要注意的是:不能再app.component.ts中添加该装饰器,否则启动报错。

image.png
d. 在app.module中去掉HomePage,AboutPage,ContactPage的declarations申明h和entryComponents中的引用。
import { NgModule, ErrorHandler } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';import { MyApp } from './app.component';import { StatusBar } from '@ionic-native/status-bar';import { SplashScreen } from '@ionic-native/splash-screen';
@NgModule({ declarations: [
MyApp, // 去掉
//AboutPage,
//ContactPage,
//HomePage,
//TabsPage
], imports: [
BrowserModule,
IonicModule.forRoot(MyApp)
], bootstrap: [IonicApp], entryComponents: [
MyApp, // 去掉
//AboutPage,
//ContactPage,
//HomePage,
//TabsPage
], providers: [
StatusBar,
SplashScreen,
{provide: ErrorHandler, useClass: IonicErrorHandler}
]
})export class AppModule {}e. OK了,到此为止懒加载配置完成,启动项目试试吧。

image.png
f. 我的项目结构图如下:

最后
在使用了懒加载之后,每一个page页面都需要一个module,并且使用到该组件的时候需要使用字符串,而不是组件类型。如上面提到的几个选项卡配置,将组件修改为字符串类型。
作者:旧城城旧
链接:https://www.jianshu.com/p/3c1caba4eb3d
随时随地看视频