> Markdown version of [Caricamento dinamico dei fogli di stile](https://vaadin.com/docs/latest/it/styling/advanced/dynamic-stylesheets). Section index: [llms.txt](https://vaadin.com/docs/latest/it/styling/llms.txt)

# Caricamento dinamico dei fogli di stile

I fogli di stile possono essere caricati dinamicamente in base alla logica dell’applicazione sul lato server. Questo può essere utile, ad esempio, per caricare stili in base all’utente corrente, o per consentire all’utente di passare manualmente tra temi diversi.

Questo si fa usando il metodo `addStyleSheet` sulla classe `Page`, che accetta un parametro URL. L’URL può puntare a un foglio di stile servito dall’applicazione stessa, situato nella cartella delle risorse `src/main/resources/META-INF/resources` (o in `src/main/webapp` per app non-Spring pacchettizzate come WAR), oppure a un URL esterno.

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

I file caricati in questo modo vengono applicati all’intera UI nella sessione corrente, e rimangono applicati fino alla fine della sessione.

Per caricare un foglio di stile aggiunto dinamicamente in modo che i suoi stili perdano sempre rispetto al resto degli stili dell’applicazione indipendentemente dalla specificità dei selettori, use the three-argument overload of `addStyleSheet` to put it in a CSS cascade layer (V25.4 pre-release). Il secondo argomento è il [load mode](https://vaadin.com/docs/latest/it/flow/advanced/loading-resources.md#flow.loading-resources.load-mode); `LoadMode.EAGER` è il valore predefinito usato dagli altri overload.

```java
UI.getCurrentOrThrow().getPage().addStyleSheet(
        "vendor-widgets.css", LoadMode.EAGER, "vendor.widgets");
```

Passare `null` come layer per caricare il foglio di stile senza alcun layer, come fanno gli altri overload di `addStyleSheet`. Vedere [Stylesheets](https://vaadin.com/docs/latest/it/styling/stylesheets.md) per maggiori informazioni sui cascade layer.

I fogli di stile dinamici possono essere rimossi usando l’istanza `Registration` restituita dal metodo `addStyleSheet`.

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

Usando il caricamento dinamico e la registration è possibile avere una funzionalità di stile sostituibile.

Questo può essere usato, ad esempio, in un componente `StyleChanger` per aggiornare lo stile corrente in base alla selezione dell’utente.

Il codice di esempio definisce gli stili `default`, `color vision deficiency` e `compact`, per i quali i file di stile effettivi si troverebbero in `src/main/resources/META-INF/resources/`

```java
public class ThemeChanger extends Select<String> {
    public ThemeChanger() {
        setLabel("Select Theme");
        setItems("default-style.css", "cvd-style.css", "compact-style.css");
        setValue("default-style.css");

        addValueChangeListener(event -> switchTheme(
                event.getSource().getUI().orElse(UI.getCurrentOrThrow()),
                event.getValue()));
    }

    @Override
    protected void onAttach(AttachEvent attachEvent) {
        super.onAttach(attachEvent);
        UI ui = attachEvent.getUI();
        Registration registration = ComponentUtil.getData(ui,
                Registration.class);
        // set default-style if no registration found
        if (registration != null) {
            switchTheme(ui, "default-style.css");
        }
    }

    /**
     * Switch the current theme style sheet for a new one.
     *
     * @param ui         the ui in use, not {@code null}
     * @param styleSheet new style to replace current with
     */
    protected void switchTheme(UI ui, String styleSheet) {
        // Get previous style registration
        Registration registration = ComponentUtil.getData(ui,
                Registration.class);
        // If previous available remove style sheet
        if (registration != null) {
            registration.remove();
        }

        // Add the new style sheet
        registration = ui.getPage().addStyleSheet(styleSheet);

        // Store registration to remove style on later change
        ComponentUtil.setData(ui, Registration.class, registration);
    }
}
```

`6c72d9f9-16d5-4ab5-add8-3c481c3103f8`
