cache directive retains the rendered DOM subtree for a template even when it is not currently displayed. When the active template switches back to a previously rendered one, the cached DOM is restored rather than re-created from scratch.
Import
Signature
Parameters
The value to render — typically a
TemplateResult. When the template changes, the previous template’s DOM is moved into an off-screen cache. When a previously cached template becomes active again, its DOM is restored from the cache. Non-template values are passed through directly without caching.Return type
DirectiveResult — an opaque value consumed by lit-html’s template engine.
How it works
Withoutcache, switching between two templates destroys the old DOM and creates new DOM every time:
cache, the first template’s DOM is moved to a DocumentFragment when it is replaced, and restored from there when it becomes active again:
strings array (the static parts of the tagged template literal), so each unique template definition gets its own cache entry.
Example
Performance tradeoffs
cache trades memory for render time. Cached DOM nodes are held in memory even when not displayed.Use cache when:- The templates being toggled are expensive to create (complex components, large subtrees).
- The user is likely to switch back and forth frequently.
cache when:- Memory usage is a concern (e.g., mobile devices, many cached templates).
- The toggled templates are simple and cheap to recreate.
- Each render produces a different template structure (the cache will never be hit).