如何提高Angular2应用程序的加载性能?

时间:2022-10-11 03:22:54

Angular2 app is loading slow, how can I improve the performance on load?

Angular2应用程序加载缓慢,如何提高负载性能?

I use Angular2, typescript with html5.

我使用Angular2,打字稿和html5。

currently my app takes 4 seconds to load. I host with Firebase and use cloudflare.

目前我的应用程序需要4秒钟加载。我使用Firebase托管并使用cloudflare。

Things I'm doing / info:

我正在做的事情/信息:

  • I've compressed images.
  • 我压缩了图像。
  • I minify css
  • 我缩小了CSS
  • I minify js.
  • 我缩小了js。
  • I use async on my scripts.
  • 我在脚本上使用async。
  • My scripts are in my .
  • 我的脚本在我的。
  • The scripts are around 700kb
  • 脚本大约700kb
  • I used google speed test and get 65%
  • 我使用谷歌速度测试获得65%
  • I used minified version of the libs I use e.g. bootstrap etc.
  • 我使用了我使用的libs的缩小版本,例如引导等
  • Using systemjs.
  • 使用systemjs。
  • This is the seed app im using: https://github.com/mgechev/angular-seed
  • 这是使用的种子应用程序:https://github.com/mgechev/angular-seed

Flow:

流:

When the app loads it shows a blue screen (this is the bootstrap css) and then 4 seconds later the app loads and works really fast. But takes 4 seconds to load. It seems the app.js file that systemjs minifies to is slowing the whole app, and not showing the views fast enough.

当应用程序加载时,它会显示一个蓝屏(这是bootstrap css),然后4秒后应用程序加载并且工作得非常快。但需要4秒钟才能加载。似乎systemjs缩小的app.js文件正在减慢整个应用程序,并且没有足够快地显示视图。

This is my website speed test: https://www.webpagetest.org/result/161206_F5_N87/

这是我的网站速度测试:https://www.webpagetest.org/result/161206_F5_N87/

This is my website:

这是我的网站:

https://thepoolcover.co.uk/

https://thepoolcover.co.uk/

Let me know if you need more information about my app and any other things I can do.

如果您需要有关我的应用程序的更多信息以及我可以执行的任何其他操作,请告诉我。

5 个解决方案

#1


8  

How about "code splitting".

如何“代码分裂”。

From the Webpack site:

从Webpack站点:

"For big web apps it’s not efficient to put all code into a single file, especially if some blocks of code are only required under some circumstances. Webpack has a feature to split your codebase into “chunks” which are loaded on demand. Some other bundlers call them “layers”, “rollups”, or “fragments”. This feature is called “code splitting”.

“对于大型网络应用程序,将所有代码放入单个文件并不高效,特别是在某些情况下只需要某些代码块.Webpack有一个功能可以将您的代码库拆分为按需加载的”块“。其他一些捆绑包称它们为“层”,“汇总”或“碎片”。此功能称为“代码分割”。

Link here:

链接在这里:

https://webpack.github.io/docs/code-splitting.html

https://webpack.github.io/docs/code-splitting.html

Note that the Angular CLI uses Webpack.

请注意,Angular CLI使用Webpack。

Also, make sure that if your app bootstraps with data calls, that you are not holding up the rendering of your components waiting on those calls to return. Promises, async, etc.

此外,请确保如果您的应用程序使用数据调用进行引导,则表明您没有阻止等待这些调用返回的组件的呈现。承诺,异步等

#2


98  

A single page application generally takes more time while loading as it loads all necessary things at once.

单个页面应用程序通常在加载时需要更多时间,因为它会立即加载所有必需的东西。

I had also faced same problem and my team has optimized our project from loading in 8 seconds to 2 seconds by using following methods.

我也面临同样的问题,我的团队通过使用以下方法优化了我们的项目,从8秒加载到2秒。

  1. Lazy loading a module : Lazy loading modules helps to decrease the startup time. With lazy loading our application does not need to load everything at once, it only needs to load what the user expects to see when the app first loads. Modules that are lazily loaded will only be loaded when the user navigates to their routes. Angular2 has introduced modules in its final release RC5. See below for step-by-step guide.

    延迟加载模块:延迟加载模块有助于减少启动时间。使用延迟加载,我们的应用程序不需要一次加载所有内容,它只需要加载用户在应用程序首次加载时期望看到的内容。只有当用户导航到他们的路线时,才会加载延迟加载的模块。 Angular2在其最终版本RC5中引入了模块。请参阅下面的分步指南。

  2. Aot Compilation : With AoT, the browser downloads a pre-compiled version of the application. The browser loads executable code so it can render the application immediately, without waiting to compile the app first.

    Aot编译:使用AoT,浏览器会下载应用程序的预编译版本。浏览器加载可执行代码,以便它可以立即呈现应用程序,而无需先等待编译应用程序。

    It reduces the payload size : There's no need to download the Angular compiler if the app is already compiled. The compiler is roughly half of Angular itself, so omitting it dramatically reduces the application payload. For more info see this.

    它减少了有效负载大小:如果已经编译了应用程序,则无需下载Angular编译器。编译器大约是Angular本身的一半,因此省略它会大大降低应用程序的负载。有关详细信息,请参阅此

  3. Webpack : Webpack is a popular module bundler, a tool for bundling application source code in convenient chunks and for loading that code from a server into a browser. You can configure your Angular 2 web application with webpack (see this guide).

    Webpack:Webpack是一种流行的模块捆绑器,一种用于将应用程序源代码捆绑在方便的块中以及将该代码从服务器加载到浏览器中的工具。您可以使用webpack配置Angular 2 Web应用程序(请参阅本指南)。

  4. Remove scripts,stylesheet from index.html : Remove all scripts and stylesheet which are not needed in index.html. You can load these script dynamically in component itself by calling a service.

    从index.html中删除脚本,样式表:删除index.html中不需要的所有脚本和样式表。您可以通过调用服务在组件本身中动态加载这些脚本。

    Make a file script.service.ts which can load any script on demand for that component

    创建一个文件script.service.ts,它可以根据需要加载该组件的任何脚本

\script.service.ts

\ script.service.ts

import { Injectable } from '@angular/core';
declare var document: any;

@Injectable()
export class Script {

  loadScript(path: string) {
    //load script
    return new Promise((resolve, reject) => {
      let script = document.createElement('script');
      script.type = 'text/javascript';
      script.src = path;
      if (script.readyState) {  //IE
        script.onreadystatechange = () => {
          if (script.readyState === "loaded" || script.readyState === "complete") {
            script.onreadystatechange = null;
            resolve({ loaded: true, status: 'Loaded' });
          }
        };
      } else {  //Others
          script.onload = () => {
            resolve({ loaded: true, status: 'Loaded' });
          };
      };
      script.onerror = (error: any) => resolve({ loaded: false, status: 'Loaded' });
      document.getElementsByTagName('head')[0].appendChild(script);
    });
  }
}

This is just a sample code to load script dynamically, you can customize and optimize it by yourself according to your need. For stylesheet you should load it in component using styleUrl.

这只是动态加载脚本的示例代码,您可以根据需要自行定制和优化脚本。对于样式表,您应该使用styleUrl将其加载到组件中。

  1. Use Browser Caching : Your webpage files will get stored in the browser cache when you use browser caching. Your pages will load much faster for repeat visitors and so will other pages that share those same resources. For more info https://varvy.com/pagespeed/leverage-browser-caching.html

    使用浏览器缓存:使用浏览器缓存时,您的网页文件将存储在浏览器缓存中。对于重复访问者,您的页面加载速度会快得多,共享相同资源的其他页面也会加载得更快。有关详细信息,请访问https://varvy.com/pagespeed/leverage-browser-caching.html

  2. minimize the code in app.component.ts : minimize the code present in app.component.ts which always run when the app loads or reloads.

    最小化app.component.ts中的代码:最小化app.component.ts中存在的代码,该代码在应用程序加载或重新加载时始终运行。

  3. set data on app Initialization : if you are using same api calls multiple times in your project or in components, or you are dependent upon same data in multiple component, instead of calling api multiple times what you can do is save the data as an object in service on app initialization. That service will act as a singleton throughout the project and you can access that data without calling api.

    在app上设置数据初始化:如果你在项目或组件中多次使用相同的api调用,或者你依赖于多个组件中的相同数据,而不是多次调用api,你可以将数据保存为对象在应用程序初始化服务。该服务将在整个项目中充当单例,您可以在不调用api的情况下访问该数据。


Lazy loading of modules step by step

延迟加载模块一步一步

  1. Modular structure : We have to divide our App into separate modules. For example an app may have a user side and an admin side and each will have its own different components and routes, so we will separate this two sides into modules admin.module.ts and user.module.ts.

    模块化结构:我们必须将我们的应用程序划分为单独的模块。例如,一个应用程序可能有一个用户端和一个管理员端,每个应用程序都有自己不同的组件和路由,因此我们将这两个侧面分为admin.module.ts和user.module.ts模块。

  2. Root Module : Every Angular app has a root module class. By convention it's a class called AppModule in a file named app.module.ts , this module will import the above two module and also the AppComponent for bootstrap. You can also declare multiple components according to your need. Sample code in app.module.ts:

    根模块:每个Angular应用程序都有一个根模块类。按照惯例,它是一个名为app.module.ts的文件中名为AppModule的类,该模块将导入上述两个模块以及AppComponent以进行引导。您还可以根据需要声明多个组件。 app.module.ts中的示例代码:

\app.module.ts

\ app.module.ts

import { NgModule } from '@angular/core';
import { UserModule } from './user/user.module';
import { AdminModule } from './admin/admin.module';
import { AppComponent } from './app.component';
import { LoginComponent } from './login.component';

@NgModule({
  imports: [UserModule, AdminModule],
  declarations: [AppComponent, LoginComponent],
  bootstrap: [AppComponent]
})
export class AppModule { }
  1. Routes : Now in your routes you can specify like the following
  2. 路线:现在在您的路线中,您可以指定如下

\app.router.ts

\ app.router.ts

import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { LoginComponent } from './login.component';

const routes: Routes = [
  { path: 'login', component: 'LoginComponent' }, //eager loaded
  { path: 'admin', loadChildren: './admin/admin.module#AdminModule' }, // Lazy loaded module
  { path: 'user', loadChildren: './user/user.module#UserModule' }  //lazy loaded module
];

Now when the application loads, it will only load LoginComponent and AppComponent code. These modules will only be loaded when we visit /admin or /user routes. Hence it will decrease the size of payload for loading into the browser, thus resulting in fast loading.

现在,当应用程序加载时,它只会加载LoginComponent和AppComponent代码。只有在访问/ admin或/ user路由时才会加载这些模块。因此,它将减少用于加载到浏览器中的有效载荷的大小,从而导致快速加载。

  1. Nesting Modules : Just like app.module every module has its own set of components and routes. As your project becomes larger, the nesting of modules inside module is the best way to optimize because we can lazily load those modules whenever we require.
  2. 嵌套模块:就像app.module一样,每个模块都有自己的一组组件和路由。随着项目变得越来越大,模块内部模块的嵌套是优化的最佳方式,因为我们可以在需要时懒洋洋地加载这些模块。

PLEASE NOTE

请注意

Above code is only for explanation, please refer for full example https://angular-2-training-book.rangle.io/handout/modules/lazy-loading-module.html

以上代码仅供参考,请参阅完整示例https://angular-2-training-book.rangle.io/handout/modules/lazy-loading-module.html

#3


5  

It is difficult to diagnose the precise problem you are having without hands-on to your entire code base and backend (as others have suggested, the problem may not be angular at all).

如果不亲自动手操作整个代码库和后端,就很难诊断出你遇到的确切问题(正如其他人所说的那样,问题可能根本没有角度)。

Having said that, I HIGHLY recommend you start using the angular-cli. It was designed by the angular team to accomplish all of the things you need to do in a easy-to-use command line interface. So my answer is predicated on the use of the angular-cli.

话虽如此,我强烈建议你开始使用angular-cli。它由角度团队设计,可以在易于使用的命令行界面中完成您需要完成的所有操作。所以我的答案取决于使用angular-cli。

Here are the general things you can do to optimize your ng2 project for production:

以下是优化ng2项目进行生产的一般事项:

1) Ahead of Time (AoT) Compilation - Bundling/Minification/Tree-shaking

1)提前(AoT)编译 - 捆绑/缩小/树木摇晃

Look, forget about the headache of configuring a bunch of gulp tasks to accomplish all of these things. The angular-cli handles Bundling/Minification/Tree-shaking/AOT compilation in one easy step:

看,忘记配置一堆gulp任务来完成所有这些事情的头痛。 angular-cli只需一个简单步骤即可处理Bundling / Minification / Tree-shaking / AOT编译:

ng build -prod -aot

ng build -prod -aot

This will produce the following js files in your "dist" folder:

这将在“dist”文件夹中生成以下js文件:

inline.d41d8cd98f00b204e980.bundle.js
vendor.d41d8cd98f00b204e980.bundle.js
main.d41d8cd98f00b204e980.bundle.js
styles.4cec2bc5d44c66b4929ab2bb9c4d8efa.bundle.css
You will also get the gzipped versions of these files for MORE optimization:

inline.d41d8cd98f00b204e980.bundle.js.gz
vendor.d41d8cd98f00b204e980.bundle.js.gz
main.d41d8cd98f00b204e980.bundle.js.gz

Angular's AOT compilation will automatically do "tree shaking" on your code and get rid of any unused references. For example, you may use lodash in your project, but you probably only use a few lodash functions; tree shaking will trim away all the unused parts of lodash that are not needed in your final build. And most importantly, AOT compilation will pre-compile all of your code and views which means LESS time the browser needs to get the ng2 app rolling. Click here for more info on angular's AOT compilation.

Angular的AOT编译将自动对您的代码进行“树摇动”,并删除任何未使用的引用。例如,您可以在项目中使用lodash,但是您可能只使用了一些lodash函数;树摇晃将修剪掉你最终构建中不需要的所有未使用过的lodash部分。最重要的是,AOT编译将预编译所有代码和视图,这意味着浏览器需要很长时间才能使ng2应用程序滚动。点击此处了解有关角度AOT编译的更多信息。

2) Lazy loading parts of your app If you further carve up your app into different parts, you do not need to load EVERYING when your app first loads. You can specify different modules for your application that then can be bundled (by the angular-cli aot compiler) into different chunks. Read up here to learn how to organize your project into modules that you can compile into chucks that are only loaded AS NEEDED. Angular-cli will manage the creation of these chunks for you.

2)延迟加载应用程序的部分如果您进一步将应用程序划分为不同的部分,则无需在应用程序首次加载时加载每个部分。您可以为应用程序指定不同的模块,然后可以将这些模块(通过angular-cli aot编译器)捆绑到不同的块中。请阅读此处以了解如何将项目组织成模块,您可以将这些模块编译为仅按需要加载的卡盘。 Angular-cli将为您管理这些块的创建。

3) Angular Universal Now if you really want to make your load time EXTREMELY fast then you will want to consider implementing Angular Universal, which is when you compile your initial view ON THE SERVER. I have not used Angular Universal as I have been able to achieve fast load times with steps 1 and 2. But it is an exciting option in the ng2 toolset. Keep in mind you don't compile or run the ng2 app on the server, you compile the initial view serverside so the user quickly receives a jolt of html and thus the user PERCEIVES the load time to be very fast (even though a full load will still lag behind a little bit). This step does not obviate the need for the other steps. As a bonus, Angular Universal also is supposed to help with SEO.

3)Angular Universal现在,如果你真的想让你的加载时间非常快,那么你会想要考虑实现Angular Universal,这是在编译服务器上的初始视图时。我没有使用Angular Universal,因为我已经能够通过步骤1和2实现快速加载时间。但它在ng2工具集中是一个令人兴奋的选项。请记住,您不在服务器上编译或运行ng2应用程序,您编译初始视图服务器端,以便用户快速收到一个html,因此用户感知加载时间非常快(即使满载仍然会落后一点)。该步骤不会消除对其他步骤的需要。作为奖励,Angular Universal也应该帮助SEO。

4) Secondary bundling

4)二次捆绑

If I am not using lazy loading, I usually go ahead and further bundle the distribution files that are generated from AOT compilation. Thus I create one main.bundle.js file that concats inline.js, vendor.js and main.js files. I use gulp for this.

如果我没有使用延迟加载,我通常会继续捆绑从AOT编译生成的分发文件。因此,我创建了一个main.bundle.js文件,该文件汇编了inline.js,vendor.js和main.js文件。我用gulp这个。

#4


2  

because its SPA and angular 2 init too slow. thats it. plus RXjs, tons of polifills etc. AOT can help but a lot of angular2 libs do not work with it. angular universal realy helps

因为它的SPA和角度2 init太慢。而已。加上RXjs,大量的polifill等AOT可以提供帮助,但很多angular2 libs都无法使用它。角度通用真的有帮助

#5


-2  

Try disabling source maps by running ng serve --sourcemap=false

尝试通过运行ng serve --sourcemap = false来禁用源映射

#1


8  

How about "code splitting".

如何“代码分裂”。

From the Webpack site:

从Webpack站点:

"For big web apps it’s not efficient to put all code into a single file, especially if some blocks of code are only required under some circumstances. Webpack has a feature to split your codebase into “chunks” which are loaded on demand. Some other bundlers call them “layers”, “rollups”, or “fragments”. This feature is called “code splitting”.

“对于大型网络应用程序,将所有代码放入单个文件并不高效,特别是在某些情况下只需要某些代码块.Webpack有一个功能可以将您的代码库拆分为按需加载的”块“。其他一些捆绑包称它们为“层”,“汇总”或“碎片”。此功能称为“代码分割”。

Link here:

链接在这里:

https://webpack.github.io/docs/code-splitting.html

https://webpack.github.io/docs/code-splitting.html

Note that the Angular CLI uses Webpack.

请注意,Angular CLI使用Webpack。

Also, make sure that if your app bootstraps with data calls, that you are not holding up the rendering of your components waiting on those calls to return. Promises, async, etc.

此外,请确保如果您的应用程序使用数据调用进行引导,则表明您没有阻止等待这些调用返回的组件的呈现。承诺,异步等

#2


98  

A single page application generally takes more time while loading as it loads all necessary things at once.

单个页面应用程序通常在加载时需要更多时间,因为它会立即加载所有必需的东西。

I had also faced same problem and my team has optimized our project from loading in 8 seconds to 2 seconds by using following methods.

我也面临同样的问题,我的团队通过使用以下方法优化了我们的项目,从8秒加载到2秒。

  1. Lazy loading a module : Lazy loading modules helps to decrease the startup time. With lazy loading our application does not need to load everything at once, it only needs to load what the user expects to see when the app first loads. Modules that are lazily loaded will only be loaded when the user navigates to their routes. Angular2 has introduced modules in its final release RC5. See below for step-by-step guide.

    延迟加载模块:延迟加载模块有助于减少启动时间。使用延迟加载,我们的应用程序不需要一次加载所有内容,它只需要加载用户在应用程序首次加载时期望看到的内容。只有当用户导航到他们的路线时,才会加载延迟加载的模块。 Angular2在其最终版本RC5中引入了模块。请参阅下面的分步指南。

  2. Aot Compilation : With AoT, the browser downloads a pre-compiled version of the application. The browser loads executable code so it can render the application immediately, without waiting to compile the app first.

    Aot编译:使用AoT,浏览器会下载应用程序的预编译版本。浏览器加载可执行代码,以便它可以立即呈现应用程序,而无需先等待编译应用程序。

    It reduces the payload size : There's no need to download the Angular compiler if the app is already compiled. The compiler is roughly half of Angular itself, so omitting it dramatically reduces the application payload. For more info see this.

    它减少了有效负载大小:如果已经编译了应用程序,则无需下载Angular编译器。编译器大约是Angular本身的一半,因此省略它会大大降低应用程序的负载。有关详细信息,请参阅此

  3. Webpack : Webpack is a popular module bundler, a tool for bundling application source code in convenient chunks and for loading that code from a server into a browser. You can configure your Angular 2 web application with webpack (see this guide).

    Webpack:Webpack是一种流行的模块捆绑器,一种用于将应用程序源代码捆绑在方便的块中以及将该代码从服务器加载到浏览器中的工具。您可以使用webpack配置Angular 2 Web应用程序(请参阅本指南)。

  4. Remove scripts,stylesheet from index.html : Remove all scripts and stylesheet which are not needed in index.html. You can load these script dynamically in component itself by calling a service.

    从index.html中删除脚本,样式表:删除index.html中不需要的所有脚本和样式表。您可以通过调用服务在组件本身中动态加载这些脚本。

    Make a file script.service.ts which can load any script on demand for that component

    创建一个文件script.service.ts,它可以根据需要加载该组件的任何脚本

\script.service.ts

\ script.service.ts

import { Injectable } from '@angular/core';
declare var document: any;

@Injectable()
export class Script {

  loadScript(path: string) {
    //load script
    return new Promise((resolve, reject) => {
      let script = document.createElement('script');
      script.type = 'text/javascript';
      script.src = path;
      if (script.readyState) {  //IE
        script.onreadystatechange = () => {
          if (script.readyState === "loaded" || script.readyState === "complete") {
            script.onreadystatechange = null;
            resolve({ loaded: true, status: 'Loaded' });
          }
        };
      } else {  //Others
          script.onload = () => {
            resolve({ loaded: true, status: 'Loaded' });
          };
      };
      script.onerror = (error: any) => resolve({ loaded: false, status: 'Loaded' });
      document.getElementsByTagName('head')[0].appendChild(script);
    });
  }
}

This is just a sample code to load script dynamically, you can customize and optimize it by yourself according to your need. For stylesheet you should load it in component using styleUrl.

这只是动态加载脚本的示例代码,您可以根据需要自行定制和优化脚本。对于样式表,您应该使用styleUrl将其加载到组件中。

  1. Use Browser Caching : Your webpage files will get stored in the browser cache when you use browser caching. Your pages will load much faster for repeat visitors and so will other pages that share those same resources. For more info https://varvy.com/pagespeed/leverage-browser-caching.html

    使用浏览器缓存:使用浏览器缓存时,您的网页文件将存储在浏览器缓存中。对于重复访问者,您的页面加载速度会快得多,共享相同资源的其他页面也会加载得更快。有关详细信息,请访问https://varvy.com/pagespeed/leverage-browser-caching.html

  2. minimize the code in app.component.ts : minimize the code present in app.component.ts which always run when the app loads or reloads.

    最小化app.component.ts中的代码:最小化app.component.ts中存在的代码,该代码在应用程序加载或重新加载时始终运行。

  3. set data on app Initialization : if you are using same api calls multiple times in your project or in components, or you are dependent upon same data in multiple component, instead of calling api multiple times what you can do is save the data as an object in service on app initialization. That service will act as a singleton throughout the project and you can access that data without calling api.

    在app上设置数据初始化:如果你在项目或组件中多次使用相同的api调用,或者你依赖于多个组件中的相同数据,而不是多次调用api,你可以将数据保存为对象在应用程序初始化服务。该服务将在整个项目中充当单例,您可以在不调用api的情况下访问该数据。


Lazy loading of modules step by step

延迟加载模块一步一步

  1. Modular structure : We have to divide our App into separate modules. For example an app may have a user side and an admin side and each will have its own different components and routes, so we will separate this two sides into modules admin.module.ts and user.module.ts.

    模块化结构:我们必须将我们的应用程序划分为单独的模块。例如,一个应用程序可能有一个用户端和一个管理员端,每个应用程序都有自己不同的组件和路由,因此我们将这两个侧面分为admin.module.ts和user.module.ts模块。

  2. Root Module : Every Angular app has a root module class. By convention it's a class called AppModule in a file named app.module.ts , this module will import the above two module and also the AppComponent for bootstrap. You can also declare multiple components according to your need. Sample code in app.module.ts:

    根模块:每个Angular应用程序都有一个根模块类。按照惯例,它是一个名为app.module.ts的文件中名为AppModule的类,该模块将导入上述两个模块以及AppComponent以进行引导。您还可以根据需要声明多个组件。 app.module.ts中的示例代码:

\app.module.ts

\ app.module.ts

import { NgModule } from '@angular/core';
import { UserModule } from './user/user.module';
import { AdminModule } from './admin/admin.module';
import { AppComponent } from './app.component';
import { LoginComponent } from './login.component';

@NgModule({
  imports: [UserModule, AdminModule],
  declarations: [AppComponent, LoginComponent],
  bootstrap: [AppComponent]
})
export class AppModule { }
  1. Routes : Now in your routes you can specify like the following
  2. 路线:现在在您的路线中,您可以指定如下

\app.router.ts

\ app.router.ts

import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { LoginComponent } from './login.component';

const routes: Routes = [
  { path: 'login', component: 'LoginComponent' }, //eager loaded
  { path: 'admin', loadChildren: './admin/admin.module#AdminModule' }, // Lazy loaded module
  { path: 'user', loadChildren: './user/user.module#UserModule' }  //lazy loaded module
];

Now when the application loads, it will only load LoginComponent and AppComponent code. These modules will only be loaded when we visit /admin or /user routes. Hence it will decrease the size of payload for loading into the browser, thus resulting in fast loading.

现在,当应用程序加载时,它只会加载LoginComponent和AppComponent代码。只有在访问/ admin或/ user路由时才会加载这些模块。因此,它将减少用于加载到浏览器中的有效载荷的大小,从而导致快速加载。

  1. Nesting Modules : Just like app.module every module has its own set of components and routes. As your project becomes larger, the nesting of modules inside module is the best way to optimize because we can lazily load those modules whenever we require.
  2. 嵌套模块:就像app.module一样,每个模块都有自己的一组组件和路由。随着项目变得越来越大,模块内部模块的嵌套是优化的最佳方式,因为我们可以在需要时懒洋洋地加载这些模块。

PLEASE NOTE

请注意

Above code is only for explanation, please refer for full example https://angular-2-training-book.rangle.io/handout/modules/lazy-loading-module.html

以上代码仅供参考,请参阅完整示例https://angular-2-training-book.rangle.io/handout/modules/lazy-loading-module.html

#3


5  

It is difficult to diagnose the precise problem you are having without hands-on to your entire code base and backend (as others have suggested, the problem may not be angular at all).

如果不亲自动手操作整个代码库和后端,就很难诊断出你遇到的确切问题(正如其他人所说的那样,问题可能根本没有角度)。

Having said that, I HIGHLY recommend you start using the angular-cli. It was designed by the angular team to accomplish all of the things you need to do in a easy-to-use command line interface. So my answer is predicated on the use of the angular-cli.

话虽如此,我强烈建议你开始使用angular-cli。它由角度团队设计,可以在易于使用的命令行界面中完成您需要完成的所有操作。所以我的答案取决于使用angular-cli。

Here are the general things you can do to optimize your ng2 project for production:

以下是优化ng2项目进行生产的一般事项:

1) Ahead of Time (AoT) Compilation - Bundling/Minification/Tree-shaking

1)提前(AoT)编译 - 捆绑/缩小/树木摇晃

Look, forget about the headache of configuring a bunch of gulp tasks to accomplish all of these things. The angular-cli handles Bundling/Minification/Tree-shaking/AOT compilation in one easy step:

看,忘记配置一堆gulp任务来完成所有这些事情的头痛。 angular-cli只需一个简单步骤即可处理Bundling / Minification / Tree-shaking / AOT编译:

ng build -prod -aot

ng build -prod -aot

This will produce the following js files in your "dist" folder:

这将在“dist”文件夹中生成以下js文件:

inline.d41d8cd98f00b204e980.bundle.js
vendor.d41d8cd98f00b204e980.bundle.js
main.d41d8cd98f00b204e980.bundle.js
styles.4cec2bc5d44c66b4929ab2bb9c4d8efa.bundle.css
You will also get the gzipped versions of these files for MORE optimization:

inline.d41d8cd98f00b204e980.bundle.js.gz
vendor.d41d8cd98f00b204e980.bundle.js.gz
main.d41d8cd98f00b204e980.bundle.js.gz

Angular's AOT compilation will automatically do "tree shaking" on your code and get rid of any unused references. For example, you may use lodash in your project, but you probably only use a few lodash functions; tree shaking will trim away all the unused parts of lodash that are not needed in your final build. And most importantly, AOT compilation will pre-compile all of your code and views which means LESS time the browser needs to get the ng2 app rolling. Click here for more info on angular's AOT compilation.

Angular的AOT编译将自动对您的代码进行“树摇动”,并删除任何未使用的引用。例如,您可以在项目中使用lodash,但是您可能只使用了一些lodash函数;树摇晃将修剪掉你最终构建中不需要的所有未使用过的lodash部分。最重要的是,AOT编译将预编译所有代码和视图,这意味着浏览器需要很长时间才能使ng2应用程序滚动。点击此处了解有关角度AOT编译的更多信息。

2) Lazy loading parts of your app If you further carve up your app into different parts, you do not need to load EVERYING when your app first loads. You can specify different modules for your application that then can be bundled (by the angular-cli aot compiler) into different chunks. Read up here to learn how to organize your project into modules that you can compile into chucks that are only loaded AS NEEDED. Angular-cli will manage the creation of these chunks for you.

2)延迟加载应用程序的部分如果您进一步将应用程序划分为不同的部分,则无需在应用程序首次加载时加载每个部分。您可以为应用程序指定不同的模块,然后可以将这些模块(通过angular-cli aot编译器)捆绑到不同的块中。请阅读此处以了解如何将项目组织成模块,您可以将这些模块编译为仅按需要加载的卡盘。 Angular-cli将为您管理这些块的创建。

3) Angular Universal Now if you really want to make your load time EXTREMELY fast then you will want to consider implementing Angular Universal, which is when you compile your initial view ON THE SERVER. I have not used Angular Universal as I have been able to achieve fast load times with steps 1 and 2. But it is an exciting option in the ng2 toolset. Keep in mind you don't compile or run the ng2 app on the server, you compile the initial view serverside so the user quickly receives a jolt of html and thus the user PERCEIVES the load time to be very fast (even though a full load will still lag behind a little bit). This step does not obviate the need for the other steps. As a bonus, Angular Universal also is supposed to help with SEO.

3)Angular Universal现在,如果你真的想让你的加载时间非常快,那么你会想要考虑实现Angular Universal,这是在编译服务器上的初始视图时。我没有使用Angular Universal,因为我已经能够通过步骤1和2实现快速加载时间。但它在ng2工具集中是一个令人兴奋的选项。请记住,您不在服务器上编译或运行ng2应用程序,您编译初始视图服务器端,以便用户快速收到一个html,因此用户感知加载时间非常快(即使满载仍然会落后一点)。该步骤不会消除对其他步骤的需要。作为奖励,Angular Universal也应该帮助SEO。

4) Secondary bundling

4)二次捆绑

If I am not using lazy loading, I usually go ahead and further bundle the distribution files that are generated from AOT compilation. Thus I create one main.bundle.js file that concats inline.js, vendor.js and main.js files. I use gulp for this.

如果我没有使用延迟加载,我通常会继续捆绑从AOT编译生成的分发文件。因此,我创建了一个main.bundle.js文件,该文件汇编了inline.js,vendor.js和main.js文件。我用gulp这个。

#4


2  

because its SPA and angular 2 init too slow. thats it. plus RXjs, tons of polifills etc. AOT can help but a lot of angular2 libs do not work with it. angular universal realy helps

因为它的SPA和角度2 init太慢。而已。加上RXjs,大量的polifill等AOT可以提供帮助,但很多angular2 libs都无法使用它。角度通用真的有帮助

#5


-2  

Try disabling source maps by running ng serve --sourcemap=false

尝试通过运行ng serve --sourcemap = false来禁用源映射