Skip to content

feat(DomRenderer): allow partial DOM hydration from pre-rendered content #13446

Closed

Description

@jeffbcross

I'm recapping a discussion I just had with @alxhub and @tbosch. This is mostly Tobias' design.

I'm submitting a ... (check one with "x")

[x] feature request

Current behavior

Typically when a page is pre-rendered, such as with Universal, the Angular application bootstraps in the browser, then blows away the pre-rendered content, and replaces it with newly created nodes. The DOM tree that is pre-rendered is often very similar, or identical to the DOM tree created on the front end, but there are issues that make it difficult for Angular to take over the existing DOM tree (otherwise referred to as DOM hydration).

The actual handoff of destroying the old DOM and showing the new DOM is pretty fast and seamless, so it's not necessarily a major UX issue in and of itself. Where it becomes problematic is in cases like ads that load in iframes (which is pretty much all display ads). If these ad iframes are pre-rendered -- which is a business requirement for many publishers -- and the iframe gets moved in the DOM, the iframe will refresh. This causes some ad networks to suspect abuse, as if publishers are trying to sneak more ad views.

Why Not Use the Already-Rendered DOM?

One issue is that with asynchronicity+conditional DOM (i.e. *ngIf="data | async"), the tree in the client may be rendered before the condition is truthy, whereas the pre-rendered version may have the full tree with async data resolved.

Another challenge is that text nodes are not able to be selected by CSS selectors, which would mean the renderer would have to rely on child ordering in order to associate pre-rendered nodes with client-rendered nodes (which is not always correct). Similar challenge goes for elements in an *ngFor, the order must be assumed to be identical.

The renderer would also be responsible for cleaning up pre-rendered orphan nodes. i.e. if 30 items in an *ngFor were pre-rendered, but only 20 were rendered in the client, the additional 10 nodes would need to be removed to prevent unexpected behavior.

Proposal: Optional, explicit, partial DOM Hydration

Allow setting a user-specified attribute on elements to associate the pre-rendered version with client-rendered version. If the renderer comes to a node that it can't associate with an existing node, it will blow away the node and re-create it. The developer would be responsible for setting these ids on the elements they care about. Example:

import { HydrateDomConfig, NgModule } from '@angular/core';

@NgModule({
  providers: [
    { 
      provide: HydrateDomConfig, 
      useValue: {
        hydrate: true, // default false for backwards compat
        attribute: 'pid', // default 'id'
      } 
    }
  ]
})

Component:

@Component({
  template: `
    <div pid="header">
      <header-ad pid="header-ad"></header-ad>
      <div>
        <!-- this will get blown away and re-created since it lacks attribute -->
      </div>
    </div>
  `
})

This design allows the DomRenderer to traverse the DOM tree and match elements for each branch starting at the root until it can't go any deeper, at which point it would blow away the descendants and re-create them.

Text nodes would all be destroyed and re-created with this design, as well as any node that doesn't have the set attribute, pid.

I don't expect that the rendering would be user-perceivable, other than if there are discrepancies between pre-rendered and client-rendered DOM, but that's a concern even without this feature.

CC @gdi2290 @pxwise

@tbosch & @alxhub please feel free to add anything I missed (or misrepresented).

Activity

  1. added
    area: core
    feature
    on Dec 14, 2016
  2. pxwise commented on Dec 14, 2016

    @pxwise

    Ad wipeout on client bootstrap is a real world issue for us using universal and this hydration proposal should solve it. Our current workaround gets us partway there, moving server DOM into the same position in client rendered DOM but does not outsmart ad verification services that watch for DOM mutations, hiding the ad upon client bootstrap.

    Big thumbs up for opt-in hydration.

  3. PatrickJS commented on Dec 14, 2016

    @PatrickJS
    Contributor

    LGTM, Keep in mind this is a huge problem with all js frameworks so for Angular to have a solution is a great win for when comparing different SSR solutions. The real solution is having Ads actually work together with js frameworks but that will never happen, other than AMP. I can see how it would be implemented by rewriting selecting root element and providing a different render path.

    For the |async you definitely have that problem with Promises due to the microtask while Observables do return synchronously. On the client, we can assume there will be batched data sent from the server to the client which gives us all of the results immediately. For Universal, we need to have the data available to the client synchronously anyways to reuse the server Http responses

    var res = {data: 'ok'};
    var api = Rx.Observable.of(res);
    var api2 = Promise.resolve(res);
    
    var vm = {};
    var vm2 = {};
    api.subscribe(function(data) { vm = data; });
    api2.then(function(data) { vm2 = data; });
    console.log(vm); // {data: 'ok'}
    console.log(vm2); // {}
  4. jeffbcross commented on Dec 14, 2016

    @jeffbcross
    ContributorAuthor

    An alternative design would be to provide an alternate renderer that would extend DomRenderer, rather than modifying DomRenderer to behave differently depending on the hydrate value.

    @NgModule({
      providers: [{
        provide: Renderer, useClass: DomHydrationRenderer
      }]
    })
  5. PatrickJS commented on Dec 15, 2016

    @PatrickJS
    Contributor

    +1 for DomHydrationRenderer

  6. IgorMinar commented on Dec 16, 2016

    @IgorMinar
    Contributor

    Two things:

    • angular.io v42 might also benefit from this. I had to put in a bunch of code that prevented some flickering caused by the content being wiped out by the renderer code when initializing components
    • I wonder if there is something from the AMP solution that we could leverage to in universal, it would be good to look into that before we go too creative with our own solution/workaround.
  7. playground commented on Dec 19, 2016

    @playground

    +1 either solution will be beneficial and vital for us to move forward.

  8. tbosch commented on Dec 28, 2016

    @tbosch
    Contributor

    We can still make the work generically, when using auto generated ids based on the place in the element hierarchy (and not based on the creation order).

    I think we should think this through as well before we decide.

  9. FahadMullaji commented on Jan 10, 2017

    @FahadMullaji

    is HydrateDomConfig part of @angular/core? I get error when I try to compile the application.

    error TS2305: Module '"/home/fahad/Workspace/siteCuriouss/node_modules/@angular/core/index"' has no exported member 'HydrateDomConfig'.

  10. DzmitryShylovich commented on Jan 10, 2017

    @DzmitryShylovich
    Contributor

    @FahadMullaji it's only a proposal.

  11. josephliccini commented on Aug 29, 2017

    @josephliccini

    This proposal is super exciting!

    Has any thought been given to pre-rendered lazy routes? We can achieve pre rendered lazy routes via https://github.com/angular/universal/blob/master/modules/ng-module-map-ngfactory-loader/README.md

    Is it possible for the hydration to occur after lazy route is fetched and then rendering begins?

    Just curious on thoughts here.

    Universal has been great and straightforward to use so far; thanks to everyone involved!

  12. mcferren commented on Sep 24, 2017

    @mcferren

    What couples the ComponentRef obj to the Dom string (cmpref.changeDetectorRef.rootNodes[0] & cmpref.hostView.rootNodes[0] ect)? Is there an explicit reference(i.e. dom string selector) or does this binding live in memory? Is there a possibility of calling createComponent with an existing dom node as an argument?

  13. added this to the Backlog milestone on Jan 23, 2018
  14. 168 remaining items

  15. PatrickJS commented on Feb 17, 2024

    @PatrickJS
    Contributor

    can we close this issue. there's no reason to keep this open

  16. princ09 commented on Feb 17, 2024

    @princ09
  17. princ09 commented on Feb 17, 2024

    @princ09
  18. denisyilmaz commented on Feb 17, 2024

    @denisyilmaz
  19. princ09 commented on Feb 17, 2024

    @princ09
  20. denisyilmaz commented on Feb 17, 2024

    @denisyilmaz
  21. bierzorutas commented on Feb 17, 2024

    @bierzorutas
  22. princ09 commented on Feb 17, 2024

    @princ09

    Thanks @bierzorutas and @denisyilmaz for your input.
    @denisyilmaz that font flickering is happening because of font-display : swap property. That can be another issue with hydration.
    I would love to hear from contributor and developer of Angular, please have look into this code. Let me know what I am missing here.

  23. alxhub commented on Mar 30, 2024

    @alxhub
    Member

    Closing as resolved :)

    Note that the original issue is not describing partial hydration, but a workaround for the issues with the destructive "hydration" that Angular had originally, to allow partial reuse of some of the DOM during the client-side bootstrapping.

    Partial hydration is indeed on our roadmap, but that's not what this issue tracks :)

  24. PatrickJS commented on Mar 30, 2024

    @PatrickJS
    Contributor

    yes, the future merging with Wiz is amazing.

    Everything I wanted for Angular Universal is finally happening and it's exciting to see 🎉

    There are more things, I'll share in the future, that are only possible with Resuming frameworks and Signals so I'm glad Angular can be part of that 🙌

    I want to thank everyone who believed in me with Angular Universal and the vision I had for it.
    Angular has a bright future ahead 🥂

    image

  25. JeanMeche commented on Mar 30, 2024

    @JeanMeche
    Member

    image

  26. naveedahmed1 commented on Mar 30, 2024

    @naveedahmed1
    Contributor

    Wow, what a historic moment! Farewell, dear issue! 🎉 It feels like saying goodbye to an old friend we've been following since 2016. The bond we've formed over the years, the ups and downs, the anticipation... it's been quite the journey! 😄 Though I'll miss our regular updates, I'm excited for the next chapter in Angular's evolution. Cheers to the closure and onwards to partial hydration! 🚀 #Goodbye2016Issue #HelloPartialHydration

  27. angular-automatic-lock-bot commented on Apr 30, 2024

    @angular-automatic-lock-bot

    This issue has been automatically locked due to inactivity.
    Please file a new issue if you are encountering a similar or related problem.

    Read more about our automatic conversation locking policy.

    This action has been performed automatically by a bot.

  28. locked and limited conversation to collaborators on Apr 30, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area: serverfeaturefeature: under considerationstate: Needs Design

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions