In AnQiCMS, optimizing the 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 a highly efficient method to solve this problem, which allows images not to be loaded until they enter the user's field of view, thereby speeding up the initial rendering 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 for your website by using simple template configuration combined with frontend JavaScript.

Understand the principle of image lazy loading

The core idea of image lazy loading is to defer loading the image resources that are not within the viewport. Usually, the browser will immediately download all<img>TagssrcThe image specified by the property. And lazy loading technology stores the actual address of the image.data-src/data-originaletc. custom properties, andsrcThe property points to a lightweight placeholder image (even if it is empty). When the user scrolls the page and the image is about to enter the visible area, the frontend JavaScript code captures this event and thendata-srcthe actual image address to.srcEnglish picture starts downloading and displaying.

How does AnQiCMS support lazy loading of article content images?

AnQiCMS in handling the article detail page content, provides a built-in mechanism to assist in implementing lazy loading of images. This is mainly reflected inarchiveDetailtag pairsContentthe rendering of fields.

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

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

To enable lazy loading, AnQiCMS allows you to add aarchiveDetailofContentfield.lazyParameter. This parameter is used to inform AnQiCMS, in rendering the article content,<img>to be displayedsrcthe content of the attribute is replaced to the custom attribute you specified, andsrcProperties are cleared or set to a placeholder.

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

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

Here,lazy="data-src"Represents that AnQiCMS will move all<img>Tagssrcto contentdata-srcattributes, andsrcattributes may be cleared.|safeThe filter is necessary here, it indicates that AnQiCMS treats the output HTML content as safe content without escaping, to ensure that image tags are rendered correctly.

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

Front-end JavaScript implementation of lazy loading steps

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

  1. Choose an appropriate lazy loading library or native support:Modern browsers already support it natively:loading="lazy"Property, this is the simplest and highest performance** solution. You can add it in<img>the tag directlyloading="lazy". When using AnQiCMS,lazy="data-src"if your JS lazy loading library can also loaddata-srcwithsrcwhilesrcwhich also containsloading="lazy",then it can be used 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 APIEnglish polyfill solution. These libraries will usually listen to scroll events or useIntersection Observer APIto detect element visibility.

  2. 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 template conventions of AnQiCMS, static resource files are usually stored in/public/static/Directory. You can add it in 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-srcwithsrc,you can introduce a simple custom JS like this:

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

    or, 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 used to illustrate the lazy loading logic.In practical applications, you may need to configure and initialize in more detail according to the official documentation of the selected lazy loading library.

Summary of Specific Operation Process

  1. Publish or Edit Articles:When publishing or editing articles in AnQiCMS background, you can insert images normally without any special operations. The system will store these images in a standard<img>tagged format.
  2. Modify article detail page template:Find your article detail page template (usually located/template/您的模板目录/{模型table}/detail.html), and it will output the article content:archiveDetailTag modification 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 your website's public template file (for examplebase.html, usually before the<head>or</body>Before the tag(标签之前), introduce the lazy loading JavaScript library you have chosen, and initialize it according to the documentation of the library.If you use the example of the above native Intersection Observer, you can directly paste the code.

Optimization and precautions

  • Avoid lazy loading for the first screen images:For images that appear in the user's view when the page is first loaded (Above the Fold), it is not recommended to use lazy loading