Skip to content

Commit cd99a5b

Browse files
committed
Move style gathering from class finalization to initialization
By moving style gathering to initialization, stylesheets will only be created for elements that have booted, and not for elements that have only be registered. This should be performance positive for applications with less than ideal loading behaviors.
1 parent 530ea26 commit cd99a5b

File tree

6 files changed

+57
-17
lines changed

6 files changed

+57
-17
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
2020

2121
### Fixed
2222
* Properties annotated with the `eventOptions` decorator will now survive property renaming optimizations when used with tsickle and Closure JS Compiler.
23+
* Moved style gathering from `finalize` to `initialize` to be more lazy, and create stylesheets on the first instance initializing.
2324

2425
<!-- ### Changed -->
2526

src/lib/decorators.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -265,7 +265,8 @@ export function eventOptions(options: AddEventListenerOptions) {
265265
* this property should be annotated as `NodeListOf<HTMLElement>`.
266266
*
267267
*/
268-
export function queryAssignedNodes(slotName: string = '', flatten: boolean = false) {
268+
export function queryAssignedNodes(
269+
slotName: string = '', flatten: boolean = false) {
269270
return (protoOrDescriptor: Object|ClassElement,
270271
// tslint:disable-next-line:no-any decorator
271272
name?: PropertyKey): any => {

src/lib/updating-element.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -132,7 +132,8 @@ type AttributeMap = Map<string, PropertyKey>;
132132
* interface corresponding to the declared element properties.
133133
*/
134134
// tslint:disable-next-line:no-any
135-
export type PropertyValues<T = any> = keyof T extends PropertyKey ? Map<keyof T, unknown> : never;
135+
export type PropertyValues<T = any> =
136+
keyof T extends PropertyKey ? Map<keyof T, unknown>: never;
136137

137138
export const defaultConverter: ComplexAttributeConverter = {
138139

src/lit-element.ts

Lines changed: 16 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -63,19 +63,6 @@ export class LitElement extends UpdatingElement {
6363

6464
private static _styles: CSSResult[]|undefined;
6565

66-
/** @nocollapse */
67-
protected static finalize() {
68-
// The Closure JS Compiler does not always preserve the correct "this"
69-
// when calling static super methods (b/137460243), so explicitly bind.
70-
super.finalize.call(this);
71-
// Prepare styling that is stamped at first render time. Styling
72-
// is built from user provided `styles` or is inherited from the superclass.
73-
this._styles =
74-
this.hasOwnProperty(JSCompiler_renameProperty('styles', this)) ?
75-
this._getUniqueStyles() :
76-
this._styles || [];
77-
}
78-
7966
/** @nocollapse */
8067
private static _getUniqueStyles(): CSSResult[] {
8168
// Take care not to call `this.styles` multiple times since this generates
@@ -84,7 +71,10 @@ export class LitElement extends UpdatingElement {
8471
// shared styles will generate new stylesheet objects, which is wasteful.
8572
// This should be addressed when a browser ships constructable
8673
// stylesheets.
87-
const userStyles = this.styles!;
74+
const userStyles = this.styles;
75+
if (userStyles === undefined) {
76+
return [];
77+
}
8878
if (Array.isArray(userStyles)) {
8979
// De-duplicate styles preserving the _last_ instance in the set.
9080
// This is a performance optimization to avoid duplicated styles that can
@@ -109,6 +99,17 @@ export class LitElement extends UpdatingElement {
10999
return [userStyles];
110100
}
111101

102+
/** @nocollapse */
103+
private static _initializeStyles() {
104+
// Only initialize styles once per class
105+
if (this.hasOwnProperty(JSCompiler_renameProperty('_styles', this))) {
106+
return;
107+
}
108+
// Prepare styling that is stamped at first render time. Styling
109+
// is built from user provided `styles` or is inherited from the superclass.
110+
this._styles = this._getUniqueStyles();
111+
}
112+
112113
private _needsShimAdoptedStyleSheets?: boolean;
113114

114115
/**
@@ -124,6 +125,7 @@ export class LitElement extends UpdatingElement {
124125
*/
125126
protected initialize() {
126127
super.initialize();
128+
(this.constructor as typeof LitElement)._initializeStyles();
127129
(this as {renderRoot: Element | DocumentFragment}).renderRoot =
128130
this.createRenderRoot();
129131
// Note, if renderRoot is not a shadowRoot, styles would/could apply to the

src/test/lib/decorators_test.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,8 @@ import {eventOptions, property} from '../../lib/decorators.js';
1616
import {customElement, html, LitElement, PropertyValues, query, queryAll, queryAssignedNodes} from '../../lit-element.js';
1717
import {generateElementName} from '../test-helpers.js';
1818

19-
const flush = window.ShadyDOM && window.ShadyDOM.flush ? window.ShadyDOM.flush : () => {};
19+
const flush =
20+
window.ShadyDOM && window.ShadyDOM.flush ? window.ShadyDOM.flush : () => {};
2021

2122
// tslint:disable:no-any ok in tests
2223

src/test/lit-element_styling_test.ts

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -788,6 +788,40 @@ suite('Static get styles', () => {
788788
'4px');
789789
});
790790

791+
test('element class only gathers styles once', async () => {
792+
const base = generateElementName();
793+
let styleCounter = 0;
794+
customElements.define(base, class extends LitElement {
795+
static get styles() {
796+
styleCounter++;
797+
return css`:host {
798+
border: 10px solid black;
799+
}`;
800+
}
801+
render() {
802+
return htmlWithStyles`<div>styled</div>`;
803+
}
804+
});
805+
const el1 = document.createElement(base);
806+
const el2 = document.createElement(base);
807+
container.appendChild(el1);
808+
container.appendChild(el2);
809+
await Promise.all([
810+
(el1 as LitElement).updateComplete,
811+
(el2 as LitElement).updateComplete
812+
]);
813+
assert.equal(
814+
getComputedStyle(el1).getPropertyValue('border-top-width').trim(),
815+
'10px',
816+
'el1 styled correctly');
817+
assert.equal(
818+
getComputedStyle(el2).getPropertyValue('border-top-width').trim(),
819+
'10px',
820+
'el2 styled correctly');
821+
assert.equal(
822+
styleCounter, 1, 'styles property should only be accessed once');
823+
});
824+
791825
test(
792826
'`CSSResult` allows for String type coercion via toString()',
793827
async () => {

0 commit comments

Comments
 (0)