In this article, let's learn about how to
improve performance by
dynamically loading an image in Blazor WASM apps.
Note: If you have not done so already, I recommend you read the article on Printing barcode to label printer from Blazor WASM.
Table of Contents
- Use Case for Dynamic Loading
- Implementing Dynamic Loading
- Advantages of Dynamic Loading
Few months ago as of writing this article, I was observing some
performance issues in I ❤️ .NET home screen.
The home screen was taking more than 10 seconds to load as I was showing all the posters in home screen. The numbers of posters at that time was some
what close to 80+. I decided to
improve performance and reduce the load time to give better user experience to
the users. That's when I decided to load the images dynamically. When I say dynamically, I mean load the image only when it is required via a user
action. This is called
Dynamic Loading. I decided to load 5 images by default and kept remaining images inside
show more button. This drastically improved the performance and reduced the load time. In this article, I will teach you how to implement dynamic
loading in Blazor WASM apps.
Use Case for Dynamic Loading
The use case of dynamic loading are,
- Load the image only when it is required. This is useful when the image is not required immediately or load only after an interaction like button click.
- Any interaction that changes the displayed image if there is more than once.
Implementing Dynamic Loading
To implement dynamic loading, we need to store image path inside a variable in razor component and assign the image path as
<img> tag. If the path is empty we can hide the code that
sources the image. This will prevent the image from loading. The image will only be displayed to the user if the path is not empty.
Code Sample - Dynamically loading image in Blazor WASM
Demo - Dynamic Image Loading
Click on Show Image button to load the image dynamically.
Advantages of Dynamic Loading
The advantages of dynamic loading are as follows,
Faster Page load.
In this article, we learnt how to
dynamically loading image and
in Blazor WASM apps by going through the
performance issues happened in I ❤️ .NET home screen. We also learnt
about the advantages of dynamic loading and its use cases along with a demo of dynamic loading in action. I hope you enjoyed reading this article.
Thank you for reading.