How to preload angular2 views so will not flicker white page on first load?

荒凉一梦 提交于 2019-12-04 05:53:16

Add a wrapper around the <router-outlet>

<div [hidden]="!isInitialized">
  <router-outlet></router-outlet>
</div>

In the page component set isInitialized to false. Then call

this.router.navigate(['Page1'])
.then(_ => this.router.navigate(['page2']))
.then(_ => this.router.navigate(['page3']))
...
.then(_ => {
    this.isInitialized = true; 
    this.router.navigate(['Page1']);
});
Benny Bottema

Paraphrasing https://stackoverflow.com/a/37298914/441662

The problem is that the files are loaded separately, which you can prevent using something like webpack that compiles the sources into bundles which can include both your app and the templates used in the routes. (altough I still can't explain the jump to the top of the page).

Here's how you can modify the webpack config of the angular/angular2-seed project:

package.json

"devDependencies": {
  ...,
  "html-loader": "^0.4.3",
},

webpack.config.js

module: {
  loaders: [
    ...,
    { test: /\.html$/, loader: 'html' }
  ]
}

Example usage in your-component.ts

@Component({
  template: require('app/components/your-component/your-component.html')
})

Now the routes are loaded instantly and there is no flickering or jumping going on.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!