How to implement lazy loading of images in templates for AnQiCMS to enhance user experience?

As an experienced security CMS website operations personnel, I fully understand the importance of website performance for user experience and search engine ranking.Especially in the era of content being king, the loading speed of images, as an important component of content, often becomes a key factor in determining whether users stay or leave.The AnQi CMS, with its high concurrency features of Go language and SEO-friendly design, provides a solid foundation for us, and image lazy loading is an effective strategy for further optimizing the front-end experience and making the website fly.

Implementing lazy loading of images in AnQiCMS templates, significantly enhancing the user experience of the website

Under the current Internet environment, users have increasingly high expectations for web page loading speed.Pages with a large number of images often load slowly, which not only increases the waiting time for users, leading to higher bounce rates, but also has a negative impact on search engine optimization (SEO), as search engines are increasingly emphasizing page loading speed and user experience.Image lazy loading (Lazy Loading) is an effective technology to solve this problem, it can delay the loading of images in the non-visible area until they are about to enter the user's field of vision, thereby greatly improving the initial loading speed of the page and optimizing the user experience.

Anqi CMS, as a content management system focusing on efficiency and user value, provides us with friendly support and flexibility in implementing lazy loading of images in templates.This allows website operators and frontend developers to easily apply lazy loading strategies to images in the website content.

The foundation for improving website performance and user experience: lazy loading of images

The core idea of lazy loading images is 'loading on demand'.When a user visits a page, only the images within the browser's viewport are loaded immediately.Images located outside the viewport, in the 'folded area below', will start loading only when the user scrolls the page and the image is about to enter the viewport.

Firstly, it reduced the amount of network requests and data transmission during the initial load, thereby significantly shortening the initial loading time of the page.This is particularly important for mobile device users, as their network bandwidth is usually limited.Secondly, it relieved the server pressure because not all images would be requested at the first time.Finally, it optimized the website's performance metrics, such as LCP (largest contentful paint), thereby improving the ranking potential in search engines.The "Static Caching and SEO Optimization

AnQiCMS implements the strategy of lazy loading images in templates

The template engine of AnQiCMS is similar to Django syntax, using{{变量}}to output data,{% 标签 %}To control logic. The implementation of lazy loading for images, AnQi CMS mainly provides support and implementation in the following two ways:

Lazy loading handling when inserting images in the content editor

The document content generated by the built-in content editor of AnQi CMS, such as articles or product details'Contentfield is the key area for implementing image lazy loading. When calling this content, the AnqicmsarchiveDetailTags providedlazyparameter can directly place the content in<img>label'ssrcattribute is replaced withdata-srcOr other custom properties to work with the front-end lazy loading library.

The specific implementation is as follows:

{# 假设我们正在展示一篇文档的详细内容 #}
<div>
    {# 使用 archiveDetail 标签获取文档内容,并指定 lazy="data-src" #}
    {%- archiveDetail articleContent with name="Content" lazy="data-src" %}
    {# 输出内容时,确保使用 |safe 过滤器以避免HTML实体转义 #}
    {{articleContent|safe}}
</div>

Bylazy="data-src"The parameters, Anqi CMS will renderarticleContentAnd automatically identify and process the following when rendering<img>Label, move the originalsrcattribute values todata-srcthe attribute. For example:

<img src="path/to/image.jpg" alt="描述">It will be converted into<img data-src="path/to/image.jpg" alt="描述">

This is a very convenient built-in feature provided by AnQi CMS, which greatly simplifies the template integration work of lazy loading images in the content area.

Lazy loading processing is output directly in the template.

In addition to the content in the editor, website templates often directly reference images, such as the cover image of the documentLogo、ThumbnailThumbor throughImagesThe group of images obtained by the field. For these images explicitly called in the template, we need to manually adapt the lazy loading.

For example, in the document list or detail page:

{# 示例文档列表中的图片 #}
{% archiveList archives with type="list" limit="10" %}
    {% for item in archives %}
    <li>
        <a href="{{item.Link}}">
            {# 将 src 属性改为 data-src,并添加懒加载所需的 class #}
            <img class="lazyload" data-src="{{item.Thumb}}" alt="{{item.Title}}">
        </a>
    </li>
    {% endfor %}
{% endarchiveList %}

{# 示例文档详情页的封面图 #}
<div>
    {# 将 src 属性改为 data-src,并添加懒加载所需的 class #}
    <img class="lazyload" data-src="{% archiveDetail with name='Logo' %}" alt="{% archiveDetail with name='Title' %}" />
</div>

In the above example, we manually changedsrcthe attribute todata-src, and added aclass="lazyload". ThisclassIt is usually used by front-end JavaScript lazy loading libraries to identify which images need to be processed with lazy loading.

Introduce front-end JavaScript lazy loading library

The AnQi CMS template mechanism is responsible for displaying images.srcproperties todata-src(or the specified other attribute), but the actual lazy loading logic is handled by the front-end JavaScript library.You need to choose a lightweight and efficient lazy loading library and integrate it into your Anqi CMS template.lazysizes/vanilla-lazyloadOr use the native one.Intersection Observer APIImplement it yourself.

Start withlazysizesFor example, the integration steps are as follows:

  1. Download and import.lazysizes.min.js:tolazysizesThe library file is placed in your Anqi CMS static resource directory/public/static/js/below.

  2. Include JavaScript in the template:The AnQi CMS template conventions mention that public header, footer, and other code can be placed inbash.htmlAmong. This is an ideal place to include global JavaScript files.

    Inbash.htmlof<head>Inside or (or<body>before the closing tag):

    <script src="{% system with name='TemplateUrl' %}/js/lazysizes.min.js" async=""></script>
    
  3. Ensure the image tag is correct:

    • For those who passlazy="data-src"The content rendered by the parameters, AnQi CMS will automatically handle the image.data-srcProperty. Generally,lazysizeslibraries will automatically recognizedata-srcthe image of the property, and addlazyloadClass.
    • for manually written<img>Tags such asLogo/Thumb),except for thesrcchanged todata-srcoutside, it usually also needs to be addedclass="lazyload"to ensure that the library can be correctly identified. Some libraries may also require a placeholdersrcFor examplesrc="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="to prevent the browser from displaying broken image icons before the lazy loading takes effect.

Effect verification and optimization

After integrating the lazy loading feature, be sure to perform the effect verification.Use the browser developer tools (Network Tab) to observe the network requests during page loading, and you will find that images in non-visual areas are not requested during the initial page load.Only when you scroll to the position of the image, they will begin to load.

At the same time, Anqi CMS also provides other image optimization features in the "Content Settings", such as whether to enable Webp image format, whether to automatically compress large images, and various thumbnail processing methods.Combine these backend settings with front-end lazy loading technology to bring comprehensive image performance improvement to the website.

By following the detailed steps above, we can effectively implement image lazy loading in the Anqi CMS template, significantly improving the website's loading speed and user experience.This not only allows visitors to get the information they need faster, but also lays a solid foundation for the website to win better SEO performance in the fierce competition.


Frequently Asked Questions (FAQ)

1. Will lazy loading of images affect the SEO of the website?In fact, if implemented properly, lazy loading of images is positive for SEO.Modern search engine crawlers, especially Googlebot, are already able to execute JavaScript and understand lazy-loaded content.By reducing the time to first contentful paint (LCP), improving page loading speed, lazy loading helps to improve core Web Vitals metrics, which is becoming an increasingly important ranking factor for search engines.data-srcof the image URL, mainstream lazy loading libraries usually handle this point well.

2. Do I need to manually write JavaScript code in AnQi CMS to implement lazy loading of images?The AnQi CMS provides built-in support for lazy loading images in the "content area" of template rendering, throughlazy="data-src"parameters, it will automatically convertsrcproperties todata-src. However,The actual image loading logic indeed requires a frontend JavaScript library to complete.This means you need to select an existing JavaScript lazy loading library (such as lazysizes), upload its files to the static resource directory of Anqi CMS, and introduce the JS file in the template.srcWithdata-srcAnd add the corresponding CSS class.

3. Besides lazy loading images, what other features does Anqi CMS have to help me optimize image performance?Aqie CMS provides multiple image optimization features. You can configure them in the "Content Settings" backend:

  • Do you want to enable Webp image format:Automatically convert uploaded JPG, PNG, and other images to a smaller WebP format.
  • Whether to automatically compress large images:Perform on large images that exceed the preset width.