Styles are not applied to the LitElement in Safari/Firefox

Viewed 1667

Update from 01.2020: It should be fixed with https://github.com/Polymer/lit-element/pull/712

If undefined returned from render method of LitElement during the first render of the component and then lit-html TemplateResult is returned with some css classes (styles are defined in styles static getter method), these styles are not applied.

enter image description here

There is a simple JSFiddle to reproduce this issue.

If render method returns lit-html TemplateResult after first render of component, then <style> tag exists in shadow DOM. enter image description here

If render method returns undefined after first render, <style> tag is missed in shadow DOM and never added even if lit-html TemplateResult in next render call. enter image description here

For Chrome it works fine. The issue reproduces for Safari and Firefox.

UPDATE: It should be fixed with https://github.com/Polymer/lit-element/pull/712

2 Answers

The solutions is to make sure you always return lit-html TemplateResult from render method even if it's empty!

render() {
   return html``;
}

But I don't fully understand why exactly this issue appears? Could somebody clarify?

There are three separate cases of how styling is handled based on Shadow DOM support, via source code:

(1) shadowRoot polyfilled: use ShadyCSS
(2) shadowRoot.adoptedStyleSheets available: use it.
(3) shadowRoot.adoptedStyleSheets polyfilled: append styles after

That's why it can behave differently in different browsers.

LitElement has a method adoptStyles(). It applies styling to the element shadowRoot using the static get styles property.

In your example, you could call this.adoptStyles(); after changing the property and it should render correctly.

https://wicg.github.io/construct-stylesheets/#using-constructed-stylesheets

https://github.com/Polymer/lit-html/blob/master/src/lib/shady-render.ts#L127

Anyhow, I think you faced a bug within the update method of LitElement.

This could solve it: https://github.com/Polymer/lit-element/pull/849

Related