Vaadin.Router works great with code splitting. If your build tool allows
you to split your code into various bundles which can then be loaded on
demand, Vaadin.Router can load these bundled lazily just-in-time before
rendering a route.
In order to use this feature specify a bundle URL in the bundle
property of the route object.
By default Vaadin.Router loads route bundles as regular JavaScript files (async),
but it supports ES module bundles as well. In order to use a ES module as a route bundle,
set the bundle property to an object with the following structure:
Note: If the bundle URL does not end with .js nor with
.mjs, Vaadin.Router throws an Error and does not
attempt to load it. Use a custom route action as shown in the next demo if
you need to load non-js bundles.
This demo shows how to load the user.bundle.js
script which defines the custom element for the /user/:id route.
Check the network tab in the browser DevTools to see that the script is
loaded only after clicking the /user/guest link.
In cases when loading .js and .mjs is not
enough—most notably, when using HTML imports in Polymer-based
apps—the lazy loading feature can be implemented with a custom route
action (for more details see
Route Actions).
This demo shows a way to lazily add an HTML import. The user.bundle.html
file contains entire Polymer 2 component definition including a template, a class,
and a script that defines a custom element.
Vaadin.Router allows you to implement your own loading mechanism for bundles using custom Route Actions. In that case, you can use dynamic imports and a module bundler to make the code work in browsers not supporting them natively. Both Webpack and Polymer CLI support dynamic imports for lazy loading ES modules, and transform them for the older browsers.
Vaadin.Router supports splitting the routes configuration object into parts and lazily loading them on-demand, enabling developers to create non-monolithic app structures. This might be useful for implementing a distributed sub routes configuration within a big project, so that multiple teams working on different parts of the app no longer have to merge their changes into the same file.
The children property on the route config object can be set to a function, which returns an
array of the route objects. It may return a Promise, which allows to dynamically import
the configuration file, and return the children array exported from it.
See the API documentation
for detailed description of the children callback function.