Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions articles/styling/advanced/dynamic-stylesheets.adoc
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
---
title: Loading Stylesheets Dynamically
page-title: Loading Stylesheets Dynamically
description: Explains how dynamically to load stylesheets.
meta-description: Implement dynamic style loading in Vaadin Flow to optimize application performance.
order: 40
---


= Loading Stylesheets Dynamically

Stylesheets can be loaded dynamically based on application logic on the server side. This can be useful, for example, to load styles based on the current user, or to allow the user to switch between different themes, manually.

This is done using the `addStyleSheet` method on the [classname]`Page` class, which takes a URL parameter. The URL can point either to a stylesheet served by the application itself, located in the resource folder `src/main/resources/META-INF/resources`, or to an external URL.

[source,java]
----
/* Local style sheet served by the application */
/* Located in src/main/resources/META-INF/resources/dynamic-styles.css */
UI.getCurrent().getPage().addStyleSheet("dynamic-styles.css");
/* Style sheet loaded from an external URL */
UI.getCurrent().getPage().addStyleSheet("https://example.com/styles.css");
----

Note that files loaded this way are applied to the entire UI in the current session, and remain applied until the end of the session.

Check warning on line 25 in articles/styling/advanced/dynamic-stylesheets.adoc

View workflow job for this annotation

GitHub Actions / lint

[vale] reported by reviewdog 🐶 [Vaadin.NoteThat] Avoid using 'note that'. Raw Output: {"message": "[Vaadin.NoteThat] Avoid using 'note that'.", "location": {"path": "articles/styling/advanced/dynamic-stylesheets.adoc", "range": {"start": {"line": 25, "column": 1}}}, "severity": "WARNING"}

Dynamic stylesheets can be removed using the [classname]`Registration` instance returned by the `addStyleSheet` method.

[source,java]
----
/* Add dynamic stylesheet */
Registration registration = UI.getCurrent().getPage().addStyleSheet("dynamic-styles.css");
/* Remove dynamic stylesheet when it is not needed anymore */
registration.remove();
----

[discussion-id]`6c72d9f9-16d5-4ab5-add8-3c481c3103f8`
Loading