How to implement lazy loading of image content in AnQiCMS templates to optimize performance?

Calendar 👁️ 65

In the digital age, the speed of website access has become one of the key indicators for measuring user experience and search engine ranking.Images are often an important component of web content and can also be a major factor affecting page loading speed.When a page contains a large number of high-definition images, the browser needs to load all image resources before rendering the page, which undoubtedly increases the user's waiting time.This problem led to the emergence of the image lazy loading (Lazy Loading) technology.

The core idea of lazy loading images is to delay loading images that are not within the current viewport (i.e., the visible area on the user's current screen).Only when the image is about to enter or has already entered the user's viewport, should the request and loading of the real image resource begin.This strategy can significantly reduce the number of resource requests and data transmission during the first page load, thereby accelerating the rendering speed of the page, saving user bandwidth, and having a more obvious effect on improving the user experience of mobile devices. At the same time, it also helps to improve the SEO performance of the website.

AnQiCMS as a high-efficiency, customizable enterprise-level content management system took full consideration of website performance optimization from the beginning of its design.It provides a flexible template engine syntax, allowing users to finely control the display of front-end content, which greatly facilitates our implementation of image lazy loading.

AnQiCMS supports lazy loading of images in the content area

AnQiCMS's template engine syntax is similar to Django templates, controlling content output through various tags.For the content area of the article detail page, AnQiCMS provides a very convenient built-in lazy loading mechanism.When displaying article content, we can usearchiveDetaillabel'slazyParameter, allowing the system to automatically replace images in the content withsrcProperties with custom properties (for exampledata-src), and insert a placeholdersrc.

Specifically, when you usearchiveDetailtags to output document contentContentyou can write the template code like this:

{% archiveDetail articleContent with name="Content" lazy="data-src" %}
{{ articleContent|safe }}
{% endarchiveDetail %}

In this code block,lazy="data-src"The parameter will indicate the AnQiCMS template engine, during processingarticleContentWhen searching for HTML content in a variable, find all<img>tags. Once found, it will move the originalsrcattribute value to a property nameddata-srcand willsrcThe attribute is set to a default blank placeholder image address (usually a very small transparent GIF).

For example, if there was originally an image in your article content<img src="https://en.anqicms.com/uploads/images/example.jpg" alt="示例图片">Afterlazy="data-src"The processed HTML structure that will be output to the front-end page might be:

<img src="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==" data-src="https://en.anqicms.com/uploads/images/example.jpg" alt="示例图片">

At this time, the browser will only load that tiny placeholder GIF, without immediately loading the actualexample.jpg.

Extend lazy loading to other image elements

Although AnQiCMS provides built-in lazy loading for the article content area, the images on a website are not limited to the article content. For example, the thumbnails on the article list page, the cover images on the product detail page, the Banner images on the category page, etc., are usually loaded througharchiveList/archiveDetail/pageDetail/categoryDetailretrieve labels directlyLogo/ThumborImagesfields to display. For these images directly outputted through template tags, we need to make some manual adjustments.

Include the general steps to implement these lazy loading images:

  1. Modify the image tags in the template:You need to find all the images output directly (such asLogo/Thumbfields) of<img>tags, and manually change theirsrcThe attribute should be changed to a placeholder and the actual image address should be stored indata-srcthe attribute. For example, a code that originally displays an article thumbnail might be:

    <img src="{{ item.Thumb }}" alt="{{ item.Title }}">
    

    You need to change it to:

    <img src="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==" data-src="{{ item.Thumb }}" alt="{{ item.Title }}">
    

    Heredata:image/gif;base64,...It is a very small transparent GIF image, used as a temporary placeholder when the browser is loading. You can also use other loading images or custom styles as placeholders.

  2. Introduce JavaScript lazy loading logic:The next step is to add JavaScript code to listen for these withdata-srcThe image of the property. When they enter the user's viewport, the script will assigndata-srcthe real image address tosrcThe attribute triggers the loading of the image. A simple and modern implementation is to useIntersection ObserverAn API that can efficiently detect when elements enter or leave the viewport without complex scroll event listeners. You can add the following JavaScript code to your template file (for example, usually inbase.htmlthe file</body>Before the tag, or in a separate JS file and through{% system with name="TemplateUrl" %}Tag introduction):

    <script>
    document.addEventListener('DOMContentLoaded', function() {
        const lazyImages = 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;
                        // 如果有 srcset 属性也需要处理
                        if (lazyImage.dataset.srcset) {
                            lazyImage.srcset = lazyImage.dataset.srcset;
                        }
                        lazyImage.removeAttribute('data-src');
                        lazyImage.removeAttribute('data-srcset');
                        lazyImageObserver.unobserve(lazyImage);
                    }
                });
            });
    
            lazyImages.forEach(function(lazyImage) {
                lazyImageObserver.observe(lazyImage);
            });
        } else {
            // Fallback for browsers that do not support Intersection Observer
            lazyImages.forEach(function(lazyImage) {
                lazyImage.src = lazyImage.dataset.src;
                if (lazyImage.dataset.srcset) {
                    lazyImage.srcset = lazyImage.dataset.srcset;
                }
                lazyImage.removeAttribute('data-src');
                lazyImage.removeAttribute('data-srcset');
            });
        }
    });
    </script>
    

    This script will traverse all elements with the attribute after the page has loaded.data-srcproperties<img>Tag. If the browser supportsIntersection ObserverIt will create an observer to monitor these images. When the images enter the viewport, the observer callback function willdata-srcthe value tosrcand stop observing the image. For those that do not supportIntersection ObserverThe old browser, all images will be loaded immediately, ensuring compatibility.

  3. Optional CSS optimization:In order to enhance the user experience, you can also add some CSS styles for lazy-loading images.For example, give the image a minimum height to prevent the page content from jumping before the image is loaded, or add a background color/loading animation.

    img[data-src] {
        display: block; /* 避免图片下方出现空白 */
        min-height: 100px; /* 预设一个最小高度,防止页面跳动 */
        background-color: #f0f0f0; /* 占位背景色 */
        /* background-image: url('/public/static/images/loading.gif'); */ /* 也可以添加加载动画 */
        background-repeat: no-repeat;
        background-position: center;
    }
    

Implementing lazy loading overall

Related articles

How to display custom field content (such as author, source) in AnQiCMS templates?

AnQiCMS with its flexible content model and powerful template tag system provides great convenience for personalized display of website content.In website operations, we often need to add some information outside of standard fields for articles, products, or other content, such as the author of the article, source of content, product batch number, or specific SEO information.This non-standardized information, AnQiCMS calls it 'custom fields', they can make your website content more professional, detailed, and meet specific business needs.

2025-11-07

How to format the article publish timestamp into a readable date and time in AnQiCMS template?

In website content operation, the publication time of articles is often one of the focuses of users, as it not only affects the interest of users in reading but also has a potential impact on the timeliness and authority of the content.However, the time information stored in the database is usually in a machine-readable timestamp format, such as a series of numbers, which is difficult for ordinary visitors to understand.AnQiCMS fully considered this point, providing a flexible way for you to convert these timestamps into clear and easy-to-read date and time formats, greatly enhancing the user experience.

2025-11-07

How to display the friend link list in the admin panel of the AnQiCMS website?

On the AnQiCMS website, the display of the background management friends link list is a very practical feature. It not only helps to enhance the website's SEO effect, but also provides more valuable external resources for visitors.AnQiCMS provides a simple and efficient mechanism for managing and displaying these links, allowing even beginners to get started easily.

2025-11-07

How to get and display the detailed content and Banner image of a single page in the AnQiCMS template?

In AnQi CMS, it involves understanding the management methods of a single page and mastering the flexible application of template tags to retrieve and display the detailed content of a specific single page and its associated Banner image.AnQiCMS provides an intuitive admin interface and a powerful template engine, making this task simple and efficient. ### In-depth Understanding of AnQi CMS Single Page The "Single Page" feature of AnQi CMS is designed for pages with fixed structures, relatively independent content, and no frequent updates, such as "About Us", "Contact Information", "Service Introduction", and so on.

2025-11-07

How to automatically generate and display the content directory (ContentTitles) on the article detail page of AnQiCMS?

## How to automatically generate and display the content directory (ContentTitles) on the AnQiCMS article detail page??For long content, a clear table of contents (also known as "article outline" or "chapter navigation") can greatly enhance the reading experience of users.It not only helps readers quickly understand the structure of the article, but also allows them to directly jump to the chapters of interest, thereby improving the readability and user satisfaction of the content.

2025-11-07

How to get and display related article lists according to Tag ID in AnQiCMS template?

In a content management system, Tag (tag) plays an important role.They can not only help us flexibly organize content, but also associate articles with similar themes across different categories, and can effectively improve the website's internal link structure and user experience.When a user is interested in a specific topic, by clicking on a Tag, they can easily view all related articles.AnQiCMS provides a set of intuitive and powerful template tags that allow you to easily retrieve and display these related article lists based on Tag ID.

2025-11-07

How to display all the Tag tags belonging to the current article in AnQiCMS template?

Flexible display of article tags in AnQiCMS templates Tags are a highly effective content organization method in website content operation.They can not only help users find relevant content faster, enhance the browsing experience of the website, but also have an indispensable positive effect on search engine optimization (SEO).AnQiCMS as a feature-rich enterprise-level content management system naturally also provides powerful tag management and call functions, allowing us to easily display all tags associated with the current article on the article detail page.

2025-11-07

How to dynamically display the Title, Keywords, and Description information of the website homepage in AnQiCMS template?

In website operation, the Title (title), Keywords (keywords), and Description (description) of the homepage are the first impression given to users on the search engine results page (SERP) and are also the key for search engines to understand the core content of the website.They not only affect the website's search engine optimization (SEO) effect, but also directly relate to whether users will click to enter your website.AnQiCMS as a feature-rich enterprise-level content management system provides a straightforward and powerful way to manage these important SEO elements. Next

2025-11-07