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

read this post--> https://github.com/angular/universal-starter/issues/436

adheegm avatar Apr 18 '18 04:04 adheegm

@adheegm I've tried that solution but still it's not working. I made an topic on Angular repo. My problem seems to be similar. I think it only exist when you are trying to combine Service Worker and Universal together. I'm using TransferState + initialNavigation and it doesn't work also.

You can check described issue here https://github.com/angular/angular/issues/23427

patrykp57 avatar Apr 19 '18 07:04 patrykp57

finally I found the solution that worked. look at the following post: https://medium.com/@evertonrobertoauler/angular-5-universal-with-transfer-state-using-angular-cli-19fe1e1d352c

hesampour avatar Jun 05 '18 13:06 hesampour

using angular 6.0.4, even with the state transfer, the flickering will be still there:

  1. page loaded with css and with styling
  2. quick 0.1 - 0.4 sec of whiteness (even obvious with image reloading)
  3. page back with css and styling

nghenglim avatar Jul 01 '18 13:07 nghenglim

@nghenglim Have you implemented Angular 6 + Angular Universal + transfer state? I have some issues including transfer state to my code. Can you please help?

hinalshah91 avatar Jul 04 '18 06:07 hinalshah91

The following link is a complete tutorial. I implement that and thank god it is OK now. I did it for angular 6+ https://medium.com/@evertonrobertoauler/angular-5-universal-with-transfer-state-using-angular-cli-19fe1e1d352c

hesampour avatar Jul 04 '18 06:07 hesampour

@hinalshah91

yes my new blog is using angular universal and transfer state. The result is better than not using it, but flickering will be still there.

flickering-universal. make service worker update on reload and use slow 3g network and disable cache. You can see the flickering.

nghenglim avatar Jul 04 '18 08:07 nghenglim

@nghenglim That looks great! Can you provide the steps to implement the same?

hinalshah91 avatar Jul 04 '18 09:07 hinalshah91

@hinalshah91 Still enhancing the app, and it currently has a bad first meaningful paint time which is near 3000ms in my browser. Thinking it could be due to the flickering from angular which makes the time to first paint actually a bit later

nghenglim avatar Jul 04 '18 10:07 nghenglim

I spend two days to find solution and still have no idea. I also couldn't find any working example (try all linked above). For me SSR is completely unuseful in this situation, I can't deploy "flickering" app on my server. For now in my app (and each other which I tested) server returns html, and Browser app replace whole html (based on app-root tag) after load. Which, as I understand is not expected behaviour. I use APP_INITIAlIZER to prepare data before BrowserApp appears so it easy to spot 'replacing moment'.

Could you provide any, even super simple example of app, which I run on local server and which will work without html replacing? For now Im not even sure that my problem is possible to resolve. But it looks exactly the same as in @nghenglim blog example.

I work on complex app but for a sake of resolve that problem I create simple app: https://bitbucket.org/7furik7/angular-universal-test/src/master/

pawelfurman avatar Jul 04 '18 15:07 pawelfurman

@pawelfurman seems like it mainly serve for SEO purpose. However it will be awesome if the flickering can be solved.

For simplicity I also created a gif to explain the flickering with the implementation of transfer state.

flickering-universal

nghenglim avatar Jul 05 '18 01:07 nghenglim

Seems like I found that my flickering is due to lazy-module. Seems like it is fixed by using

@NgModule({
  imports: [ RouterModule.forRoot(routes, { initialNavigation: 'enabled' }) ],
  exports: [ RouterModule ]
})
export class AppRoutingModule {}

which is mentioned in https://github.com/angular/angular/issues/15716

nghenglim avatar Jul 05 '18 03:07 nghenglim

you can see my implementation with angular universal 6 and state worker. http://www.biomaze.ir

hesampour avatar Jul 05 '18 12:07 hesampour

when working with angular this problem sometimes happens. especially when you ram is full. I had more problem with ram. my ram would become full and sometimes my cpu usage. but this problem is exist in development not in production. when I have this problem I usually close all other applications.

hesampour avatar Jul 05 '18 14:07 hesampour

I am having this same issue. What is the solution for this? I dont want my DOM to render again in client since it rendered at server side. Flickering is happening. We have to check condition like “not equals Browser” for our code?

Muthu25 avatar Jul 21 '18 05:07 Muthu25

the solution is using state worker. you can check the following link: https://medium.com/@evertonrobertoauler/angular-5-universal-with-transfer-state-using-angular-cli-19fe1e1d352c

hesampour avatar Jul 22 '18 04:07 hesampour

@hesampour, the above medium.com link also works with angular 6?

hinalshah91 avatar Jul 23 '18 05:07 hinalshah91

yes. you can see my implementation in https://biomaze.org

hesampour avatar Jul 23 '18 07:07 hesampour

I am using angular 6 + universal. First page is reloading twice. Can anybody help resolve this issue?Following is my angular.json file:

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "mobilesite-ecommerce": {
      "root": "",
      "sourceRoot": "src",
      "projectType": "application",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/browser",
            "index": "src/index.html",
            "main": "src/main.ts",
            "tsConfig": "src/tsconfig.app.json",
            "polyfills": "src/polyfills.ts",
            "assets": [
              {
                "glob": "**/*",
                "input": "src/assets",
                "output": "/assets"
              },
              {
                "glob": "favicon.ico",
                "input": "src",
                "output": "/"
              }
            ],
            "styles": [
              "node_modules/bootstrap/dist/css/bootstrap.min.css",
              "src/assets/fonts.css",              
              "src/styles.scss"
            ],
            "scripts": [
              "src/assets/js/commonScript.js"
            ]
          },
          "configurations": {
            "alpha": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.alpha.ts"
                }
              ]
            },
            "production": {
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true,
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ]
            },
            "development": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.development.ts"
                }
              ]
            },
            "local": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.local.ts"
                }
              ]
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "mobilesite-ecommerce:build"
          },
          "configurations": {
            "local": {
              "browserTarget": "mobilesite-ecommerce:build:local"
            },
            "alpha": {
              "browserTarget": "mobilesite-ecommerce:build:alpha"
            },
            "production": {
              "browserTarget": "mobilesite-ecommerce:build:production"
            },
            "development": {
              "browserTarget": "mobilesite-ecommerce:build:development"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "mobilesite-ecommerce:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "karmaConfig": "./karma.conf.js",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.spec.json",
            "scripts": [
              "src/assets/js/commonScript.js"
            ],
            "styles": [
              "node_modules/bootstrap/dist/css/bootstrap.min.css",
              "src/assets/fonts.css",              
              "src/styles.scss"
            ],
            "assets": [
              {
                "glob": "**/*",
                "input": "src/assets",
                "output": "/assets"
              },
              {
                "glob": "favicon.ico",
                "input": "src",
                "output": "/"
              }
            ]
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": ["src/tsconfig.app.json", "src/tsconfig.spec.json"],
            "exclude": ["**/node_modules/**"]
          }
        },
        "server": {
          "builder": "@angular-devkit/build-angular:server",
          "options": {
            "outputPath": "dist/server",
            "main": "src/main.server.ts",
            "tsConfig": "src/tsconfig.server.json"
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ]
            },
            "local": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.local.ts"
                }
              ]
            },
            "alpha": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.alpha.ts"
                }
              ]
            },
            "development": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.development.ts"
                }
              ]
            }
          }
        }
      }
    },
    "mobilesite-ecommerce-e2e": {
      "root": "",
      "sourceRoot": "e2e",
      "projectType": "application",
      "architect": {
        "e2e": {
          "builder": "@angular-devkit/build-angular:protractor",
          "options": {
            "protractorConfig": "./protractor.conf.js",
            "devServerTarget": "mobilesite-ecommerce:serve"
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "src/tsconfig.app.json",
              "src/tsconfig.spec.json",
              "e2e/tsconfig.e2e.json"
            ],
            "exclude": ["**/node_modules/**"]
          }
        },
        "server": {
          "builder": "@angular-devkit/build-angular:server",
          "options": {
            "outputPath": "dist/server",
            "main": "src/main.server.ts",
            "tsConfig": "src/tsconfig.server.json"
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ]
            },
            "local": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.local.ts"
                }
              ]
            },
            "alpha": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.alpha.ts"
                }
              ]
            },
            "development": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.development.ts"
                }
              ]
            }
          }
        }
      }
    }
  },
  "defaultProject": "mobilesite-ecommerce",
  "cli": {},
  "schematics": {
    "@schematics/angular:class": {
      "spec": false
    },
    "@schematics/angular:component": {
      "spec": false,
      "inlineStyle": true,
      "inlineTemplate": true,
      "prefix": "app",
      "styleext": "scss"
    },
    "@schematics/angular:directive": {
      "spec": false,
      "prefix": "app"
    },
    "@schematics/angular:guard": {
      "spec": false
    },
    "@schematics/angular:module": {
      "spec": false
    },
    "@schematics/angular:pipe": {
      "spec": false
    },
    "@schematics/angular:service": {
      "spec": false
    }
  }
}

My package.json file:

{
  "name": "mobilesite-ecommerce",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve -c local",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e",
    "build:ssr": "npm run build:client-and-server-bundles && npm run webpack:server",
    "serve:ssr": "node dist/server",
    "build:client-and-server-bundles": "ng build --prod && ng run mobilesite-ecommerce:server:production",
    "webpack:server": "webpack --config webpack.server.config.js --progress --colors",
    "build:prerender": "npm run build:client-and-server-bundles && npm run webpack:server && npm run generate:prerender",
    "generate:prerender": "cd dist && node prerender",
    "serve:prerender": "cd dist/browser && http-server",
    "build:local:ssr": "npm run build:local:client-and-server-bundles && npm run webpack:local:server",
    "serve:local:ssr": "node dist/server",
    "build:local:client-and-server-bundles": "ng build -c local && ng run mobilesite-ecommerce:server:local",
    "webpack:local:server": "webpack --config webpack.server.config.js --progress --colors",
    "build:development:ssr": "npm run build:development:client-and-server-bundles && npm run webpack:development:server",
    "serve:development:ssr": "node dist/server",
    "build:development:client-and-server-bundles": "ng build -c development && ng run mobilesite-ecommerce:server:development",
    "webpack:development:server": "webpack --config webpack.server.config.js --progress --colors",
    "build:alpha:ssr": "npm run build:alpha:client-and-server-bundles && npm run webpack:alpha:server",
    "serve:alpha:ssr": "node dist/server",
    "build:alpha:client-and-server-bundles": "ng build -c alpha && ng run mobilesite-ecommerce:server:alpha",
    "webpack:alpha:server": "webpack --config webpack.server.config.js --progress --colors"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^6.0.6",
    "@angular/common": "6.0.6",
    "@angular/compiler": "6.0.6",
    "@angular/core": "6.0.6",
    "@angular/forms": "6.0.6",
    "@angular/http": "6.0.6",
    "@angular/platform-browser": "6.0.6",
    "@angular/platform-browser-dynamic": "6.0.6",
    "@angular/platform-server": "^6.0.6",
    "@angular/router": "6.0.6",
    "@angular/service-worker": "6.0.6",
    "@fortawesome/fontawesome-svg-core": "^1.2.0-11",
    "@fortawesome/free-brands-svg-icons": "^5.1.0-11",
    "@fortawesome/free-solid-svg-icons": "^5.1.0-11",
    "@ng-bootstrap/ng-bootstrap": "^2.1.1",
    "@ng-select/ng-select": "^2.3.0",
    "@nguniversal/common": "^6.0.0",
    "@nguniversal/express-engine": "^6.0.0",
    "@nguniversal/module-map-ngfactory-loader": "^6.0.0",
    "@ngx-share/core": "^6.0.1",
    "angular-6-social-login": "^1.1.1",
    "bootstrap": "^4.1.1",
    "core-js": "^2.4.1",
    "font-awesome": "^4.7.0",
    "localstorage-polyfill": "^1.0.1",
    "mock-browser": "^0.92.14",
    "moment": "^2.22.1",
    "ngx-swiper-wrapper": "^6.3.0",
    "node-sass": "^4.7.2",
    "rxjs": "^6.2.1",
    "sourcebuster": "^1.1.0",
    "ts-loader": "^4.4.1",
    "webpack-cli": "^3.0.8",
    "zone.js": "^0.8.26"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.6.8",
    "@angular/cli": "^6.0.8",
    "@angular/compiler-cli": "6.0.6",
    "@angular/language-service": "6.0.6",
    "@types/jasmine": "~2.5.53",
    "@types/jasminewd2": "~2.0.2",
    "@types/node": "~6.0.60",
    "@types/youtube": "0.0.31",
    "codelyzer": "^4.0.1",
    "express": "^4.16.3",
    "http-server": "^0.11.1",
    "jasmine-core": "~2.6.2",
    "jasmine-spec-reporter": "~4.1.0",
    "karma": "~1.7.0",
    "karma-chrome-launcher": "~2.1.1",
    "karma-cli": "~1.0.1",
    "karma-coverage-istanbul-reporter": "^1.2.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.1.2",
    "ts-node": "~3.2.0",
    "tslint": "~5.7.0",
    "typescript": "2.7.2"
  }
}

My webpack.server.config.js

const path = require("path");
const webpack = require("webpack");

// Work around for https://github.com/angular/angular-cli/issues/7200
module.exports = {
  mode: 'none',
  entry: {
    // This is our Express server for Dynamic universal
    server: './server.ts'
  },
  target: 'node',
  resolve: { extensions: ['.ts', '.js'] },
  // Make sure we include all node_modules etc
  externals: [/node_modules/],
  optimization: {
    minimize: false
  },
  output: {
    // Puts the output at the root of the dist folder
    path: path.join(__dirname, 'dist'),
    filename: '[name].js'
  },
  module: {
    rules: [
      { test: /\.ts$/, loader: 'ts-loader' },
      {
        // Mark files inside `@angular/core` as using SystemJS style dynamic imports.
        // Removing this will cause deprecation warnings to appear.
        test: /(\\|\/)@angular(\\|\/)core(\\|\/).+\.js$/,
        parser: { system: true },
      },
    ]
  },
  plugins: [
    new webpack.ContextReplacementPlugin(
      // fixes WARNING Critical dependency: the request of a dependency is an expression
      /(.+)?angular(\\|\/)core(.+)?/,
      path.join(__dirname, 'src'), // location of your src
      {} // a map of your routes
    ),
    new webpack.ContextReplacementPlugin(
      // fixes WARNING Critical dependency: the request of a dependency is an expression
      /(.+)?express(\\|\/)(.+)?/,
      path.join(__dirname, 'src'),
      {}
    )
  ]
}

hinalshah91 avatar Jul 24 '18 08:07 hinalshah91

you are using http request in your page. HTTP request fetching data happens twice, one time on the server and one time on the browser. so for this one not happen you should use angular madule transfer state. so at first import ServerModule, ServerTransferStateModule in your AppServerModule . and import BrowserTransferStateModule in your app madule. then every where in your code that you have used http request you should make a state key as the following:

` import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { TransferState, makeStateKey } from '@angular/platform-browser';

const DOGS_KEY = makeStateKey('dogs');

@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent implements OnInit {

title = 'app';

dogs: any;

constructor( private http: HttpClient, private state: TransferState ) { }

ngOnInit() { this.dogs = this.state.get(DOGS_KEY, null as any);

if (!this.dogs) {
  this.http
    .get('https://dog.ceo/api/breeds/list/all')
    .subscribe(data => {
      this.dogs = data;
      this.state.set(DOGS_KEY, data as any);
    });
}

} } `

hesampour avatar Jul 24 '18 12:07 hesampour