Objective
This recipe demonstrates the following:
- How to declare a lazily loaded widget - this is done within step 2 in the procedure section
- How to exclude a widget from the main JavaScript bundle - this is handled automatically through the Dojo CLI build tool based on the registry definition
- How to download a widget on demand, at the point at which it is needed in the application lifecycle
Procedure
- Render your widget using a string based identifier, instead of rendering the class directly:
render() {
return v('div',[
// w(MyLazyWidget, {}) // Don't do this
w('my-lazy-widget', {}) // Do this
]);
}
- In your
main
file, import and configure a registry:
import { Registry } from '@dojo/widget-core/Registry';
const registry = new Registry();
registry.define('my-lazy-widget', async () => {
const response = await import('./widgets/MyLazyWidget');
return response.default;
});
- Finally, use the
setProperties
method of your existingprojector
to associate the projector with the registry:
projector.setProperties({ registry });
The widget definition of ‘MyLazyWidget
‘ is excluded from the main output bundle. A separate network request is made to MyLazyWidget.js
on-demand, at the point at which it is rendered in the application runtime.
Further reading
The Dojo 2 Registries tutorial covers lazy loading of widgets in greater detail.