angular / preboot

Coordinate transfer of state from server to client view for isomorphic/universal JavaScript web applications
MIT License
382 stars 51 forks source link

Flicker due to styles reload #120

Closed blasco closed 3 years ago

blasco commented 3 years ago

After setting up preboot with angular 11 and universal SSR, the elements are not flickering anymore. But now the styles get reloaded, which ends up causing even a larger Largest Contentful Paint and Cumulative Layout Shift. Is this the normal behavior or styles supposed to stay and this is a problem?

Here what I see: Initially the site loads fine from the server: initial

The preload seems to take over (as this didn't use to happen, here it was just completely blank before) styles_gone

And then the styles start to load (with some of them missing until it is fully loaded) final

blasco commented 3 years ago

The solution from @vdjurdjevic worked for me:

https://github.com/angular/preboot/issues/75

Although I had to slightly updated it for it to work with angular 11:

In app.module:

  providers: [
    AuthGuardAdmin,
    {
      provide: APP_INITIALIZER,
      useFactory: function(document: HTMLDocument, platformId: Object): Function {
        return () => {
          if (isPlatformBrowser(platformId)) {
            const dom = ɵgetDOM();
            const styles: any[] = Array.prototype.slice.apply(dom.getDefaultDocument().querySelectorAll(`style[ng-transition]`));
            styles.forEach(el => {
              // Remove ng-transition attribute to prevent Angular appInitializerFactory
              // to remove server styles before preboot complete
              el.removeAttribute('ng-transition');
            });
            document.addEventListener('PrebootComplete', () => {
              // After preboot complete, remove the server scripts
              setTimeout(() => styles.forEach(el => dom.remove(el)));
            });
          }
        };
      },
      deps: [DOCUMENT, PLATFORM_ID],
      multi: true
    }
  ],

Maybe this could be included in the core code so this additional patch doesn't need to be included?

blasco commented 3 years ago

Wao, it really works like a charm now... amazing. Finally getting 100% with a SSR Angular Universal app with lots of functionality. For many months I thought it was simply impossible, but this is a game changer (thanks to this I don't have to give Next.js a try). I don't understand why this preboot tool is not give more praise in the community, it took me a really long time to find this.

image