Documentation

Documentation versions (currently viewingVaadin 24)

Lazy-loading Stylesheets in Flow

The basics of how to load large stylesheets only as needed.

Stylesheets that are only needed when a particular view or other Flow-based UI class is loaded can be lazy loaded into the UI using a @StyleSheet annotation on the class.

This can be useful to avoid loading large stylesheets up-front, but does not scope the styles to that view or class. Once the stylesheet is loaded, the styles become part of the page’s global CSS, and remain applied when the user navigates away from the view. Scoping styles to a particular view or other part of the UI needs to be done through CSS class names.

The @StyleSheet annotation takes a URL parameter that can be either a file served by the application itself, or an external URL. Local files are served from the resource folder at src/main/resources/META-INF/resources. The URL path for the resource folder root is “./”, so for example @StyleSheet(“./lazy.css”) points to a file at …/resources/lazy.css.

[project root]
└── src
    └── main
        └── resources
            └── META-INF
                └── resources
                    └── lazy-loaded.css
@StyleSheet("./lazy-loaded.css") // Local file in resource folder
@StyleSheet("https://example.com/external-styles.css")
public class MyUI extends Div {
    …
}

Note that the recommended way to load external stylesheets via URLs is through an @import directive in another stylesheet, and that it’s also possible to load stylesheets via URLs dynamically.

4a7fcdcc-2924-4bf6-964c-9ff5b5958cd9