In AnQiCMS template, how to dynamically modify the `src` attribute of HTML image tags to `data-src` for lazy loading?

In AnQiCMS, optimizing the website loading speed, especially for pages with a large number of images, is an important factor in improving user experience and search engine rankings.Image lazy loading (Lazy Load) technology is a highly efficient solution that allows pages to load images only when the user scrolls to their position, rather than loading all images at once.For AnQiCMS users, this feature has its unique convenience.

Why choose image lazy loading?

The website has too many images, especially on the article detail page or product display page, which often leads to a long initial loading time.Users may need to wait a few seconds to see the full content, which is very likely to cause user churn.

  1. Improve page loading speed:Reduce the amount of HTTP requests and data transfer at initial loading, making the page appear faster to the user.
  2. Save bandwidth:Users only load the images they actually browse, reducing unnecessary resource consumption.
  3. Improved user experience:Page content is visible faster, users don't have to wait, and the experience is smoother.
  4. Optimize SEO:Search engines are increasingly emphasizing the page loading speed, lazy loading helps improve the ranking of the website in search results.

The core method to implement lazy loading in AnQiCMS templates

AnQiCMS's template engine (similar to Django syntax) provides a very direct and convenient solution for lazy loading images in content.

Scene one: Article or product detail page main image

For images inserted into the background content editor (i.e., stored in the documentContentField image), AnQiCMS provides a built-inlazyparameter that can help us automatically convert HTML image tagssrcThe attribute converts todata-src.

When you need to display document content in a template, you usually usearchiveDetailtags to obtain document details. To enable lazy loading, you just need to addContentwhen fetchinglazy="data-src"parameter.

For example, on your document detail page template (such as{模型table}/detail.html) the code that displays the article content might be like this:

{# 假设我们正在显示当前页面的文档内容 #}
<div>
    {%- archiveDetail articleContent with name="Content" lazy="data-src" %}
    {{articleContent|safe}}
</div>

In this code block:

  • {% archiveDetail articleContent with name="Content" ... %}used to get the current document'sContentcontent and assign it toarticleContenta variable.
  • lazy="data-src"is the key point. AnQiCMS template engine handlesContentfields, it will automatically identify the<img>tag and set itssrcvalue of the properties and move it todata-srcproperties. At the same time, it usually willsrcThe property is set to a placeholder (such as a transparent gif or small logo) so that the page layout is not destroyed when the image is not loaded.
  • {{articleContent|safe}}Represents the act ofarticleContentThe content of the variable is output as HTML securely because it is obtained from the HTML rich text editor.

After processing by AnQiCMS template engine, all image tags in your document content (such as<img src="https://en.anqicms.com/uploads/image.jpg">) will be automatically changed to something like<img src="/path/to/placeholder.gif" data-src="https://en.anqicms.com/uploads/image.jpg">The form of. Next, you just need to introduce a JavaScript lazy loading library on the front end to handle thesedata-srcimages.

场景二:列表页缩略图及其他图片(如Logo、Thumb)

Except for the images in the document content, there are also many other images on the website, such as thumbnails on the article list page (item.Thumboritem.Logo), carousel images, Banner images, and so on. These images are usually notContentField, therefore, AnQiCMS built-in,lazyThe parameter will not take effect. For such images, we need to use front-end JavaScript to implement lazy loading.

The implementation approach is:

  1. In the template, put the real URL of the imagedata-srcinto the attribute, notsrcproperties.
  2. srcThe property can point to a low-quality placeholder image, or a transparent GIF image.
  3. Add a specific class to the image (for examplelazyload),方便JavaScript库识别。
  4. 在页面加载完成后,通过JavaScript懒加载库来监听这些带有Englishdata-srcThe image of the property, when it enters the user's visible area, willdata-srccopy the value backsrc, thus triggering the actual loading of the image.

For example, using the thumbnail of the article list page (using)archiveListLabel):

{# 假设这是文章列表页模板中的一个条目 #}
{% archiveList archives with type="page" limit="10" %}
    {% for item in archives %}
        <li>
            <a href="{{item.Link}}">
                <h5>{{item.Title}}</h5>
                {# 这里是列表项的缩略图,手动设置data-src #}
                {% if item.Thumb %}
                <img class="lazyload" src="/static/images/placeholder.gif" data-src="{{item.Thumb}}" alt="{{item.Title}}">
                {% else %}
                <img class="lazyload" src="/static/images/placeholder.gif" data-src="/static/images/default-thumb.gif" alt="{{item.Title}}">
                {% endif %}
                <div>{{item.Description}}</div>
            </a>
        </li>
    {% endfor %}
{% endarchiveList %}

In the above code:

  • we give<img>Label has been addedclass="lazyload".
  • src="/static/images/placeholder.gif"It is a placeholder image path preset.
  • data-src="{{item.Thumb}}"ordata-src="/static/images/default-thumb.gif"It stores the actual image URL.

The selection and integration of Lazy Loading JavaScript libraries

In order to let the abovedata-srcThe image has taken effect, you need to introduce a lightweight JavaScript lazy loading library. There are many excellent libraries available, such asvanilla-lazyload/lozad.jsThey are usually very compact and easy to configure.

The integration steps are roughly as follows:

  1. Include library files:In your public template files (such asbase.html) of<body>The JavaScript file is introduced before the label ends, either via CDN or local files for lazy loading.
    
    {# 在 base.html 文件底部,</body> 标签前引入 #}
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/lazyload.min.js"></script>
    <script>
        // 初始化懒加载库
        document.addEventListener("DOMContentLoaded", function() {
            var lazyLoadInstance = new LazyLoad({
                elements_selector: ".lazyload" // 匹配所有带有lazyload类的元素
            });
        });
    </script>
    
  2. Initialize the library:According to the documentation of the library you choose, after the page is loaded (usuallyDOMContentLoadedevent) for initialization, and specify the image selector to be listened to (for example.lazyload).

Attention Points and **Practice

  • Native lazy loadingloading="lazy":Modern browsers (such as Chrome, Firefox) already support nativeloading="lazy"properties. For projects that do not need to be compatible with old browsers, you can directly in<img>tagloading="lazy"This property can be combined with the JavaScript lazy loading library as a progressive enhancement solution.
    
    <img src="/static/images/placeholder.gif" data-src="{{item.Thumb}}" alt="{{item.Title}}" loading="lazy">
    
    When the browser supportsloading="lazy"When it is available, it will prefer to load using the native method; when not supported, the JavaScript library will take over.
  • Fallback without JavaScript support:Consider those users who have disabled JavaScript. It is possible in<noscript>tags to place images with realsrcimages, or place them at the beginning of thesrcThe property is set to a low-quality version of the image, ensuring that the image can be displayed even without JS (although it is not lazy-loaded).
  • Placeholder: Using an appropriate placeholder can prevent blank or jumping layouts of page content before images are loaded, enhancing user experience. It can be a small blurred image, a solid color background, or the website logo.
  • Image size preset:To avoid layout shift (Cumulative Layout Shift, CLS), it is recommended in<img>the tag to set explicitlywidthandheightProperties, or allocate space for the image container using CSS. This helps the browser calculate the layout before the image is loaded.
  • Comprehensive test:Test the lazy loading effect on different browsers and devices to ensure that images load normally and improve page performance.

By means of the above method, you can flexibly implement lazy loading of images in the AnQiCMS template, whether by utilizing its built-inlazyParameter processing content image, or manually configure other imagesdata-srcAnd combined with front-end JavaScript libraries, it can effectively improve the performance and user experience of the website.


Common Questions (FAQ)

  1. AnQiCMSlazy参数会自动处理所有图片吗?

    • AnQiCMS template'slazyparameters (such as)lazy="data-src")主要用于处理从内容字段(比如文章或产品详情页的正文ContentField) the obtained HTML image. For images outputted directly through the template,{{item.Logo}}/{{item.Thumb}}etc., you need to manually place them intodata-srcProperty, and implement lazy loading with front-end JavaScript libraries.
  2. How to ensure that lazy loading works in all browsers, including those with JavaScript disabled?

    • For users who disable JavaScript, you can provide a fallback solution. A common practice is to<img>TagssrcPlace a low-quality or small placeholder in the property. A more sophisticated solution is to utilize<noscript>Label: In the normal<img>After the label,<noscript>Add a block containing a realsrcof<img>Label. So, if JavaScript is disabled, the browser will parse<noscript>the images. At the same time, consider using the browser'sloading="lazy"properties for progressive enhancement.
  3. Does lazy loading affect the SEO of a website?

    • The implementation of lazy loading correctly usually has a positive impact on SEO.By reducing the initial page load time, the page performance score can be improved, which is a factor that search engines value.