Lazy components

The lazy function allows us to inform Bemtv that a component must be imported through dynamic import.

This will allow us to import components only when they are really needed, thus reducing the size of our application.

lazy()

The lazy() function takes two mandatory arguments, the first is the name of the component and the second must be a function that returns the dynamic import promise:

import { _ } from "bemtv";

lazy("UserData", () => import(`./UserData`));

The lazy() function return is a function that when called executes the import and returns the promise, this can be useful in cases where we want to do the import manually, but once the component is used in some template the Bemtv will automatically import.

Fallback

Optionally, we can pass a third argument that will be used as a fallback while the component is being imported, it can be any valid value as a template:

import { _ } from "bemtv";

lazy("UserData", () => import(`./UserData`), "Loading[]");

Or a function that takes a has argument which is a boolean that informs whether the parent component of the component being imported has children:

import { _ } from "bemtv";

lazy(
  "UserData",
  () => import(`./UserData`),
  (has) => has || "Loading[]"
);

The above code would tell bemtv not to display the fallback if the parent component has children and if it does not have to display the Loading[] component, this is mainly useful for dealing with changes in routes where the route component needs to be imported but we don't want to change the DOM until it is available.

Many sites use this technique, they display a loading bar at the top, but only change the content when the component can be rendered.

Last updated