How to configure the lazy loading effect of images in the AnQiCMS article content?

Calendar 👁️ 72

In AnQiCMS, optimizing website loading speed is a key step to improve user experience and search engine rankings.When the article content contains a large number of images, these images will significantly increase the page loading time.Image lazy loading (Lazy Loading) is an efficient method to solve this problem, which allows images not to load before they enter the user's field of vision, thereby speeding up the initial rendering speed of the page.

AnQiCMS as a content management system that focuses on performance and SEO, provides flexible support for lazy loading of images in article content.You can easily enable this feature on your website by using simple template configuration combined with frontend JavaScript.

Understand the principle of image lazy loading

The core idea of lazy loading images is to delay loading the image resources within the viewport. Usually, the browser will download all<img>label'ssrcThe image specified by the attribute. Lazy loading technology stores the actual address of the image indata-src/data-originalcustom attributes, andsrcThe attribute points to a lightweight placeholder image (even if it is empty). When the user scrolls the page, the JavaScript code on the front end will capture this event and thendata-srcthe real image address tosrcThe image starts downloading and displaying.

How does AnQiCMS support lazy loading of article content images

AnQiCMS handles the detailed page content of articles and provides a built-in mechanism to assist in implementing image lazy loading. This is mainly reflected inarchiveDetailtags pairContentthe rendering of fields.

In the article detail page template, we usually usearchiveDetailtags to output the main content of the article. For example:

<div>文档内容:{% archiveDetail archiveContent with name="Content" %}{{archiveContent|safe}}</div>

To enable lazy loading, AnQiCMS allows you toarchiveDetaila tag toContentAdd a fieldlazyParameter. This parameter is used to inform AnQiCMS, in the rendering of article content in<img>when the tag is rendered,srcthe content of the attribute is replaced to the custom attribute you specified, and tosrcThe property is cleared or set to a placeholder.

Assuming you want to usedata-srcAs the storage attribute for the actual image address, you can modify your template code like this:

<div>文档内容:{% archiveDetail archiveContent with name="Content" lazy="data-src" %}{{archiveContent|safe}}</div>

Here, lazy="data-src"Indicates that AnQiCMS will move all<img>label'ssrctodata-srcproperties, at the same timesrcthe properties may be cleared.|safeThe filter is necessary here, it indicates that AnQiCMS will treat the output HTML content as safe content, without escaping, to ensure that image tags are rendered correctly.

After this step, the images in the article content will no longer be loaded directly throughsrcloading, but will wait for the intervention of front-end JavaScript.

Steps to implement lazy loading in front-end JavaScript

Simply modifying the template tags of AnQiCMS does not directly enable lazy loading of images. You also need to introduce a segment of JavaScript code to detect whether the images enter the visible area and trigger loading. This usually involves the following steps:

  1. Choose a suitable lazy loading library or native support:Modern browsers already support it nativelyloading="lazy"attribute, this is the simplest and most **performance** solution. You can add it in<img>tag directlyloading="lazy". When using AnQiCMS'slazy="data-src"if your JS lazy loading library can also loaddata-srctosrcwhilesrcwhile also containingloading="lazy"It can be used very well together. If you need to be compatible with old browsers, you can choose some lightweight frontend lazy loading libraries such asvanilla-lazyload/Lozad.jsorIntersection Observer APIA polyfill solution. These libraries usually listen to scroll events or useIntersection Observer APIto detect element visibility.

  2. to introduce JavaScript code into your template:You need to include the selected lazy loading JavaScript library file or custom JavaScript code into your website template. According to the AnQiCMS template conventions, static resource files are usually stored in/public/static/Under the directory. You can add the public header template of the website (such aspartial/header.html) or the footer template (such aspartial/footer.html, usually before the</body>tag)。“

    For example, if you use the nativeloading="lazy"and your JS logic is just todata-srctosrcyou can introduce a simple custom JS in this way:

    <!-- 引入自定义懒加载JS文件 -->
    <script src="{% system with name="TemplateUrl" %}/js/lazyload.js"></script>
    

    or, you can write the initialization code directly in HTML (not recommended for complex logic):

    <script>
    document.addEventListener("DOMContentLoaded", function() {
        var lazyImages = [].slice.call(document.querySelectorAll("img[data-src]"));
    
        if ("IntersectionObserver" in window) {
            let lazyImageObserver = new IntersectionObserver(function(entries, observer) {
                entries.forEach(function(entry) {
                    if (entry.isIntersecting) {
                        let lazyImage = entry.target;
                        lazyImage.src = lazyImage.dataset.src;
                        lazyImage.removeAttribute("data-src"); // 移除data-src属性
                        lazyImage.setAttribute("loading", "lazy"); // 添加原生懒加载属性
                        lazyImageObserver.unobserve(lazyImage);
                    }
                });
            });
    
            lazyImages.forEach(function(lazyImage) {
                lazyImageObserver.observe(lazyImage);
            });
        } else {
            // Fallback for older browsers without Intersection Observer
            // (e.g., attach to scroll, resize, orientationchange events)
            // This part can be more complex or use a dedicated library.
            let lazyLoadThrottleTimeout;
            function lazyload () {
                if (lazyLoadThrottleTimeout) {
                    clearTimeout(lazyLoadThrottleTimeout);
                }
                lazyLoadThrottleTimeout = setTimeout(function() {
                    let scrollTop = window.pageYOffset;
                    lazyImages.forEach(function (img) {
                        if (img.offsetTop < (window.innerHeight + scrollTop)) {
                            img.src = img.dataset.src;
                            img.removeAttribute("data-src");
                            img.setAttribute("loading", "lazy");
                        }
                    });
                    lazyImages = lazyImages.filter(function (img) {
                        return img.hasAttribute('data-src');
                    });
                    if (lazyImages.length == 0) {
                        document.removeEventListener("scroll", lazyload);
                        window.removeEventListener("resize", lazyload);
                        window.removeEventListener("orientationChange", lazyload);
                    }
                }, 20);
            }
    
            document.addEventListener("scroll", lazyload);
            window.addEventListener("resize", lazyload);
            window.addEventListener("orientationChange", lazyload);
        }
    });
    </script>
    

    Please note that the above JavaScript code is a simple example to illustrate the lazy loading logic.In practice, you may need to configure and initialize in detail according to the official documentation of the lazy loading library you choose.

Summary of specific operation process

  1. Post or edit article:When publishing or editing articles on the AnQiCMS backend, simply insert the pictures normally without any special operations. The system will store these images in a standardized<img>tag format.
  2. Modify the article detail page template:Find your article detail page template (usually located in/template/您的模板目录/{模型table}/detail.html), and it will output the article content:archiveDetailModify the tag to includelazy="data-src"in the form of parameters:
    
    <div class="article-content">
        {% archiveDetail articleContent with name="Content" lazy="data-src" %}{{articleContent|safe}}
    </div>
    
  3. Introduce and initialize lazy loading JavaScript:In the public template file of your website (for example)base.html, usually before the<head>or</body>Before the tag) introduce the lazy loading JavaScript library you choose, and initialize it according to the documentation of the library.If you use the above native Intersection Observer example, you can directly paste the code.

Optimization and注意事项

  • Avoid lazy loading of the first screen images:Images that appear in the user's view as the page loads (Above the Fold) are not recommended for lazy loading

Related articles

How to implement 'Previous' and 'Next' document navigation on the AnQiCMS article detail page?

In Anqi CMS, implementing the "Previous" and "Next" navigation functions on the article detail page is a key link in improving user experience, guiding users to delve deeper into the website's content, and also helps optimize the internal link structure of the website, which is greatly beneficial for SEO performance.AnQiCMS has a powerful template system and flexible tag features, making this operation intuitive and efficient.### How to implement 'Previous' and 'Next' document navigation in AnQiCMS AnQiCMS has designed a series of convenient template tags specifically for retrieving information about adjacent documents in the article detail page

2025-11-08

How to display hot articles on the AnQiCMS homepage based on article views?

On AnQiCMS, the homepage is usually the important entry point for visitors to understand the website content and quickly obtain information.Effectively display popular articles, not only to attract users' attention, improve content exposure, but also effectively enhance the user experience of the website and PV (page views).AnQiCMS with its flexible template tags and built-in features makes this operation very simple and intuitive.

2025-11-08

How to display article thumbnails in the Anqi CMS article list?

## How to Display Thumbnails Gracefully in AnQi CMS Article List Visual appeal of the article list page is crucial in website operation.A carefully selected or automatically generated thumbnail that can quickly catch the visitor's attention, convey the theme of the article, and thus improve click-through rate and optimize user experience.Our AnQi CMS provides flexible and powerful functions, helping us easily display article thumbnails in the article list.

2025-11-08

How to call and display custom parameter fields of articles in the Anqi CMS template?

In AnQi CMS, the custom parameter field of the article is an important manifestation of its core feature of 'flexible content model'.It allows us to define unique additional attributes for different types of content (such as articles, products), greatly enhancing the expressiveness of content and the customization capabilities of the website.Imagine if your website needs to display product details, in addition to the general information such as title, content, and images, you may also need specific parameters such as 'model number', 'color', 'storage capacity', and so on.These are the places where custom parameter fields take effect.

2025-11-08

How to correctly render Markdown formatted article content in AnQi CMS and display it?

Today, with the increasing efficiency in content creation, Markdown is favored by content creators for its concise syntax and focus on the content itself.AnQi CMS understands this trend and provides powerful features that allow you to easily convert Markdown-formatted article content into exquisite HTML pages and support richer display effects, such as mathematical formulas and flowcharts.

2025-11-08

How to display the associated Tag tag list on the AnQiCMS article detail page?

In website content operation, tags are important tools for connecting related content, enhancing user experience, and optimizing search engine rankings.AnQiCMS as an efficient content management system, naturally supports the association function between articles and tags.How can we clearly display these associated tags on each article's detail page to allow readers to quickly find more interesting content?This article will guide you in easily displaying the tag list on the article detail page of AnQiCMS.

2025-11-08

How to implement website in-site search and display article search results in AnQiCMS?

In website operation, the in-site search function plays a crucial role.It can not only help visitors find the information they need quickly, improve user experience, but also through the analysis of search data to understand user needs, optimize content strategy.The AnQi CMS is an efficient content management system that provides a set of intuitive and powerful mechanisms to implement site search and flexibly display search results.The on-site search function of Anqi CMS is designed to be very practical.

2025-11-08

How to display related article recommendations at the bottom of the AnQiCMS article detail page?

In AnQiCMS, adding a related article recommendation feature to the article detail page can not only effectively increase the user's stay time on the website, guide them to discover more interesting content, but also have a positive impact on the website's SEO performance.It is not difficult to achieve this function with the flexible and powerful template tag system provided by AnQiCMS. Understanding AnQiCMS Template Structure In AnQiCMS, the page layout and content display of the website are controlled by template files.

2025-11-08