fix: app ids for better <style> management for ssr (#14632)

Currently styles are rendered to the root component element, which ensures they're cleaned up automatically
when the client application is bootstrapped. This is less than ideal as progressive rendering can cause HTML
to be rendered before the CSS is loaded, causing flicker.

This change returns to rendering <style> elements in the <head>, and introduces a mechanism for removing
them on client bootstrap. This relies on associating the server and client bootstrap. Another way to think
of this is that the client, when bootstrapping an app, needs to know whether to expect a server rendered
application exists on the page, and to identify the <style> elements that are part of that app in order
to remove them.

This is accomplished by providing a string TRANSITION_ID on both server and client. For most applications,
this will be achieved by writing a client app module that imports BrowserModule.withServerTransition({appId: <id>}).
The server app module will import this client app module and therefore inherit the provider for
TRANSITION_ID. renderModule[Factory] on the server will validate that a TRANSITION_ID has been provided.
This commit is contained in:
Alex Rickabaugh
2017-02-22 16:06:21 -08:00
committed by Igor Minar
parent 830393d234
commit 88bc143431
9 changed files with 144 additions and 47 deletions

View File

@ -336,6 +336,44 @@ export function main() {
});
}));
it('should remove styles when transitioning from a server render',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
@Component({
selector: 'root',
template: 'root',
})
class RootCmp {
}
@NgModule({
bootstrap: [RootCmp],
declarations: [RootCmp],
imports: [BrowserModule.withServerTransition({appId: 'my-app'})],
})
class TestModule {
}
// First, set up styles to be removed.
const dom = getDOM();
const platform = platformBrowserDynamic();
const document = platform.injector.get(DOCUMENT);
const style = dom.createElement('style', document);
dom.setAttribute(style, 'ng-transition', 'my-app');
dom.appendChild(document.head, style);
const root = dom.createElement('root', document);
dom.appendChild(document.body, root);
platform.bootstrapModule(TestModule).then(() => {
const styles: HTMLElement[] =
Array.prototype.slice.apply(dom.getElementsByTagName(document, 'style') || []);
styles.forEach(
style => { expect(dom.getAttribute(style, 'ng-transition')).not.toBe('my-app'); });
async.done();
});
}));
it('should register each application with the testability registry',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
const refPromise1: Promise<ComponentRef<any>> = bootstrap(HelloRootCmp, testProviders);