Anatomy
Import the primitives and assemble the parts:
@using Blazix.Primitives
<AvatarRoot>
<AvatarImage Src="" />
<AvatarFallback>LT</AvatarFallback>
</AvatarRoot>Lazy-loaded images
By default, AvatarImage preloads Src and renders the image only once it has loaded. That
doesn't work with loading="lazy", or with an image component that serves a different URL than the raw
Src.
Add the KeepMounted parameter to render the image element right away and let it load in place. Only the
image that's actually displayed is requested:
<AvatarRoot class="avatar">
<AvatarFallback class="fallback">LT</AvatarFallback>
<AvatarImage KeepMounted="true" Src="/avatar.png" loading="lazy" width="32" height="32" alt="" class="image" />
</AvatarRoot>Stacking
With KeepMounted, the image and the fallback are both present until the image loads. The image is hidden
from assistive technology until then, so the fallback provides the accessible name on its own.
Stack the two in the same box, and place AvatarImage after AvatarFallback. Both are
positioned, so whichever comes later in the DOM paints on top, and the fallback shows through until the image covers
it.
A loading image paints nothing, so the fallback shows through on its own. An image that failed to load paints a
broken-image icon on top of it. Hide the image in either state with the data-loading and
data-error attributes:
.avatar {
position: relative;
}
.image,
.fallback {
position: absolute;
inset: 0;
}
.image[data-loading],
.image[data-error] {
visibility: hidden;
}
Avoid display: none here: an element without a box never intersects the viewport, so
loading="lazy" would never fetch the image. visibility and opacity both keep
lazy loading working.
API Reference
AvatarRoot
Renders a <span> element.
Other attributes are passed to the element it renders.
AvatarImage
Renders a <img> element.
Other attributes are passed to the element it renders.
AvatarFallback
Renders a <span> element.
Other attributes are passed to the element it renders.