Image Lazy Loading in ASP.NET Core Blazor


December 24, 2023 Program

Image Lazy Loading in ASP.NET Core Blazor
Document the method of implementing lazy loading of images in the Blazor framework.

Why should to use Lazy Loading in website?

🔗

Basically, the biggest reason is performance issues. If a page has 10 pictures, the user cannot actually see all the pictures at once in the operation window (screen), so if the page is loaded immediately, In order to load these 10 or more complete pictures, not only does the user have to wait for them all to be loaded, which is very time-consuming, but even worse is that the user feel stuck and don't know how to do then choose close the website. If the pictures are placed on cloud services such as S3, the accumulated data transmission costs over a long period of time will also be considerable!!

Implementation method

🔗

There are actually many ways to implement the lazy loading of pictures. The simplest is of course to limit the number of pictures loaded. Only a few pictures are loaded at a time. If you want to view more, you can slide down or click the load more button. However, this method is not enough well. After all, if the number of images loaded each time is too small, it will be very troublesome for users. If it is too many, it will not achieve the desired effect of increasing performance and reducing transmission volume.

The browser supports lazy loading, which can be achieved through this syntax。

HTML
<img src="image.jpg" loading="lazy">

But in the Blazor, it may be because all object screens have an extra layer rendered by JS. I am not sure about the actual principle, but it is invalid after testing.

The method I currently choose is to use IntersectionObserver (an API implemented by JavaScript that can monitor the status of elements in the window, that is, whether the element is within the window) to determine whether to load the image.

Code

🔗

Copy this code into the body of index.html so that every page of the website can use the lazy loading function.

JS
<!-- lzay loading -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/intersection-observer.min.js"></script>
<script type="text/javascript">
    window.lazyLoading = function () {
        const observer = new IntersectionObserver((entries, owner) => {
            for (let entry of entries) {
                if (entry.isIntersecting) {
                    // Picture enters the screen and then loads the real photo
                    const img = entry.target;
                    img.setAttribute('src', img.dataset.src);
                    img.removeAttribute('data-src');
                    owner.unobserve(img);
                }
            }
        });
        const images = document.querySelectorAll('img.lazy')
        for (let image of images) {
            observer.observe(image);
        }
    }
</script>

The main purpose is to use IntersectionObserver to determine whether the image has entered the window. If it has entered, the original src will be removed and the content of data-src will be displayed.

Website Page that require lazy loading of images (.razor):

HTML
@inject IJSRuntime js

<img src="@placeholderImage" data-src="@o.ImageUrl" class="lazy">

src is the display screen when the image is not loaded, which can be a low-resolution pixel image.
data-src is the actual image file URL to be displayed.

The part of @code is:

C#
protected override void OnAfterRender(bool firstRender)
{
    if (firstRender)
    {
        js.InvokeVoidAsync("lazyLoading");
    }
}

Used to load IntersectionObserver on first load.

Conclusion

🔗

The actual browsing effect is as follows:

You can see that when the image enters the window, the actual image will be loaded from the original default low-resolution pixel image to achieve a delayed loading effect.

BlazorCsharpJavaScriptWebSEO



Avatar

Alvin

Software engineer, interested in financial knowledge, health concepts, psychology, independent travel, and system design.

Related Posts