angular-cli icon indicating copy to clipboard operation
angular-cli copied to clipboard

First page is loaded twice in universal app

Open sravikiran opened this issue 9 years ago • 49 comments

Bug Report or Feature Request (mark with an x)

bug report

Versions.

λ ng --version @angular/cli: 1.3.0 node: 6.11.0 os: win32 x64 @angular/animations: 4.3.4 @angular/common: 4.3.4 @angular/compiler: 4.3.4 @angular/core: 4.3.4 @angular/forms: 4.3.4 @angular/http: 4.3.4 @angular/platform-browser: 4.3.4 @angular/platform-browser-dynamic: 4.3.4 @angular/router: 4.3.4 @angular/cli: 1.3.0 @angular/compiler-cli: 4.3.4 @angular/language-service: 4.3.4 @angular/platform-server: 4.3.4

λ node --version v6.11.0

λ npm --version v3.9.3

Running on Windows 10

Repro steps.

I built a sample repo using angular-cli and followed the steps in the Universal Rendering story to enable server side rendering. The application loads well on running, but I see the client rendering also happening after the page is served from the server. So the page gets rendered from the server and then the content disappears for a second as the client rendering happens.

To reproduce this, you can clone this repository, install the packages and run the following commands:

  • ng build && ng build -prod -app 1 --output-hashing none
  • node server.js

I am using the dist/index.html file instead of src/index.html, as on using the file from the src causes full page reload when I switch between the routes.

The log given by the failure.

No log, as there are no errors from npm and angular-cli

Desired functionality.

Client rendering shouldn't happen after the page is loaded from the server

sravikiran avatar Aug 23 '17 04:08 sravikiran

The server renders the page without any state and outputs static HTML to view in the browser while the angular application is being bootstrapped. A re-render when the application has been bootstrapped is required to use state saved in the browser such as logged in user information.

grizzm0 avatar Aug 23 '17 16:08 grizzm0

@grizzm0 So you are saying it is a required operation. Then is there a way in which we can prevent the flicker and to make the user's experience better?

sravikiran avatar Aug 23 '17 23:08 sravikiran

Yes, it's required. The initial page contains static HTML which needs to be replaced with your angular application once bootstrapped.

I haven't tried out universal myself yet so I don't know how bad the flicker is. Anyhow, this isn't really an issue with AngularCLI but with @angular/universal. Try searching at https://github.com/angular/angular/issues to see if anyone else has reported similar issues.

grizzm0 avatar Aug 23 '17 23:08 grizzm0

I'm also experiencing a pretty bad flicker when angular bootstraps in the browser. @sravikiran Have you found an answer somewhere else ?

matmeylan avatar Nov 17 '17 17:11 matmeylan

Relevant issues:

  • https://github.com/angular/universal-starter/issues/62
  • https://github.com/angular/universal-starter/issues/61
  • https://github.com/angular/universal-starter/issues/139
  • https://github.com/angular/universal/issues/338

mauris avatar Dec 08 '17 12:12 mauris

This issue is solved in Angular 5 release. Angular 5 has State Transfer API, that allows to send the data retrieved on server to the browser. You can read about it in the following links: https://blog.angular.io/version-5-0-0-of-angular-now-available-37e414935ced and www.dotnetcurry.com/angularjs/1388/server-side-rendering-angular-nodejs

sravikiran avatar Dec 20 '17 03:12 sravikiran

@sravikiran Thanks for that great tutorial!

For all those looking at this issue to figure out how to fix the flickering issue, I believe this is the relevant part of the article:

To make the transfer state work, the Angular application must be bootstrapped after the DOM is loaded. This is because, the data transferred from the server is stored in an HTML element and this element should be accessible to Angular to get the data. Open the file main.ts and move the application bootstrap logic inside the DOMContentLoaded event as shown below:

document.addEventListener('DOMContentLoaded', () => {  
  platformBrowserDynamic().bootstrapModule(AppModule)    
  .catch(err => console.log(err));
});

jfahrenkrug avatar Dec 20 '17 20:12 jfahrenkrug

I have the same problem. I used asp.net core at first and then upgrade my application to angular 5 and know using angular universal. but the problem still exist. and I think google dose not render my page correctly. because when I checked my page with google console it didn't show my page correctly.

I also changed all my http to new httpClient but the problem still exist

hesampour avatar Dec 28 '17 08:12 hesampour

same problem here with angular 5.2

gimox avatar Jan 15 '18 14:01 gimox

same problem here with angular 5.2

HuddleHouse avatar Jan 19 '18 16:01 HuddleHouse

That code given above by @jfahrenkrug is sometimes bugging. For example I had a problem with home page, I couldn't see view-source.

Anyway, did you get any solution for that blinking ?

patrykp57 avatar Feb 15 '18 13:02 patrykp57

@sravikiran Thanks for the great tutorial! I want to suggest an update to it:

In pokemon.service.ts :

 listPokemons() {
    let pokemons = this.state.get(POKEMONS_KEY, null as any);  //4
    if (pokemons) {
      this.state.remove(POKEMONS_KEY); // maybe add this?
      return Promise.resolve(pokemons);
    }
    return this.http.get(`${this.baseUrl}/pokedex/1/`).toPromise().then((res: any) => {
        let pokemons: Pokemon[] = [];
        let reducedPokemonEntries = res.pokemon_entries.splice(0, 50);

        reducedPokemonEntries.forEach((entry) => {
            let pokemon = new Pokemon();
            pokemon.name = entry.pokemon_species.name;
            pokemon.id = entry.entry_number;
            pokemon.imageurl = `https://rawgit.com/PokeAPI/sprites/master/sprites/pokemon/${pokemon.id}.png`;

            pokemons.push(pokemon);
    });
    if (isPlatformServer(this.platformId)) { // add this check so that state is only set when called from server
        this.state.set(POKEMONS_KEY, pokemons as any);
    }
    return pokemons;
  });
}

this.state.remove would allow the state to be cleared once it is checked. In my use case, the component loads a different article based on user interaction, and I only want to block the state once, and only when the the page is rendered on the server.

Not sure if it is a good idea to do what I did. Appreciate if anyone can point out improvements / possible mistakes in my suggestion. :)

@patrykp57 the guide works well. The page blinking/flickering has stopped for me. I implemented the guide on my own site with slight modifications as seen above.

EdwinChua avatar Feb 19 '18 08:02 EdwinChua

@gimox and @HuddleHouse did you manage to solve this issue for Angular 5.2? I am facing the same problem. Please, give me the solution if you have one.

nishadmenezes avatar Feb 21 '18 04:02 nishadmenezes

same here

tedishero avatar Feb 22 '18 00:02 tedishero

same problem here with angular 5.2

denzLLL avatar Feb 26 '18 19:02 denzLLL

I have similar problem with this issue in Angular 5.2.4. I have tried to add [RouterModule.forRoot(routes, { initialNavigation: 'enabled' })] but it didn't work either. Do anyone have any complete solution for this case?

thovo avatar Mar 07 '18 17:03 thovo

I managed to solve the double request problem (the main reason as to why the page flickers or blinks) similar to @EdwinChua 's solution, but with a HttpInterceptor between service and the backend API.

This module should help - TransferHttpCacheModule

It has a HttpInteceptor that basically does something like @EdwinChua's solution.

I modified it a bit check for urlWithParams instead of url as I send requests sometimes with different parameters and I don't need those requests to be cached. I also, modified it to un-cache a request after the second request that was triggered gets blocked.

This basically solved the flicker on Angular 5.2

nishadmenezes avatar Mar 08 '18 13:03 nishadmenezes

@nishadmenezes problem is still here!. I try first TransferHttpCacheModule it resolve some double call but not the first double call. I add the extra code for state followin the Angular universal github guide but double cal on first page is here!

 /**
   * Get all data from http and clean it
   * transferstate is a patch, remove when universal is more stable.
   *
   *
   * @returns {Observable<DataModel>}
   */
  getData(key: string, params = null): Observable<any> {

    const PAGEID_KEY = makeStateKey<string>(key);

    // we have a trasferState data
    if (this.transferState.hasKey(PAGEID_KEY)) {

      const res = this.transferState.get(PAGEID_KEY, null);
      this.transferState.remove(PAGEID_KEY);

      return Observable.of(res);
    }

    // need to get data from http
    return this.http.get(`${environment.apiUrl}/frontend/${key}`, {params: params})
      .do(pages => {

        if (this.isServer) {
          this.transferState.set(PAGEID_KEY, pages);
        }

        return pages;
      });
  }

it' like the browser render a not processed html page first and after a 0.500 ms get the real page from server.

The only think i can do now is to add a preloading full screen page that hide after all data received in browser. It's not a good solution!!

gimox avatar Mar 08 '18 14:03 gimox

sometimes its because of your routing. check for your routing that may be you redirect the first page to another component or module.

hesampour avatar Mar 09 '18 03:03 hesampour

I have same issue

masoudline avatar Apr 08 '18 15:04 masoudline