Tags: Images Optimizely CMS

Lazy loading images in Episerver/Optimizely xhtml string properties

Lazy loading of images is a technique where a website's images are loaded only when they are needed, instead of loading them up front. If the visitor never scrolls to the bottom of the page, there is no need to load that image at the very bottom.

The main reason for implementing lazy loading is to improve performance, but cost reduction may also be a valid motivation.

History

Lazy loading used to be hard! There are long descriptions like «The Complete Guide to Lazy Loading Images» that look very complicated and are way over my head.

Don't worry - the future is here!

Today most browsers support native lazy loading using the loading attribute. Adding lazy loading is as easy as adding loading="lazy" to your image tag. Like this:

<img src="image.jpg" loading="lazy" alt="I'm lazy!" width="250" height="250">

In Episerver/Optimizely

In your view files where you are in complete control of your markup, you may add loading="lazy" as you wish. But what about images added to rich text (xhtml string properties) edited with TinyMCE?

I just added it to my blog. Have a look at another post with more images to see it in action!

I simply added an extension method that rewrites all image tags.

public static class XhtmlStringExtensions
{
   public static XhtmlString AddLazyImages(this XhtmlString xhtmlString)
   {
      if (PageEditing.PageIsInEditMode)
      {
         return xhtmlString;
      }

      var processedText = Regex.Replace(
         xhtmlString.ToInternalString(),
         "(<img\\s+src=\".*?\")",
         "$1 loading=\"lazy\""
      );

      return new XhtmlString(processedText);
   }
}

Then in /Views/Shared/DisplayTemplates/ I added this as XhtmlString.cshtml:

@using EPiServer.Core
@using Gulla.Web.Extensions

@model XhtmlString

@{
    if (Model == null) { return; };
}

@{Html.RenderXhtmlString(Model.AddLazyImages());}

That's all!

Found this post helpful? Help keep this blog ad-free by buying me a coffee! ☕