How to implement lazy loading (lazyload) feature in AnQiCMS article content?

Calendar 👁️ 80

On your AnQiCMS website, optimizing image loading is a key step to improving user experience and website performance, especially for articles with a large number of image content pages.The Lazy Load (Lazy Load) technology is a highly efficient solution that allows the page to only load images within the user's viewport, while deferring the loading of images outside the viewport until the user scrolls near them.This can significantly reduce the initial page load time, save bandwidth, and improve the overall website response speed.

AnQiCMS is a system focused on enterprise-level content management and is well aware of the importance of performance optimization. Therefore, it has provided a very convenient way to implement the lazy loading of images in the output of article content.To implement this feature, it mainly involves two steps: first, configuring the content output method in the AnQiCMS template, and then integrating a simple JavaScript code on your website's frontend to handle image loading logic.

The first step: Configure image lazy loading in the AnQiCMS template

AnQiCMS uses the Django template engine syntax, which makes template customization very flexible.To enable lazy loading of images in article content, you need to edit the template file that displays article details.Generally, this file may be located in your template directory.{模型table}/detail.htmlFor example, if it is an article model, it may bearticle/detail.html.

In this template file, you will find the tags used to output the main content of the article, which is usually througharchiveDetailtags to retrieveContentfield. To support lazy loading of images, we need to addarchiveDetaila tag to addlazyParameter.

Assuming that your template originally outputs the article content like this:

{% archiveDetail articleContent with name="Content" %}
{{ articleContent|safe }}

To enable lazy loading, you just need toarchiveDetailthe tag withlazy="data-src"Parameters, like this:

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

Herelazy="data-src"Tells AnQiCMS, when it renders article content within the<img>do not use tags directly,srcattribute to load images, instead of placing the original URL in a nameddata-srcin the custom attribute. For example, one that originally is<img src="https://en.anqicms.com/uploads/image.webp" alt="示例图片">image tag, after being processed by AnQiCMS, will become<img data-src="https://en.anqicms.com/uploads/image.webp" alt="示例图片">.

Please note,|safeThe filter is indispensable here, it tells the template engine,articleContentThe variable contains safe HTML content that should be output directly rather than escaping. If missing|safeYou might see the image tag itself displayed, rather than the actual image.

You can replace it with other custom attributes according to your front-end lazy loading library requirements, such asdata-srcreplacing it with other custom properties, such asdata-originalordata-image-srcWait, it should be compatible with the JavaScript lazy loading library you choose. However,data-srcis a very common and recommended choice.

Step two: Integrate front-end JavaScript lazy loading logic

AnQiCMS completes template rendering, and willsrcattribute is replaced withdata-srcAfter that, the front-end JavaScript code needs to “read” thesedata-srcproperties, and when the image enters the user's viewport, it willdata-srcAssign the value againsrctrigger the actual loading of the image.

Here we provide a modern Web API-based solutionIntersection ObserverIt does not require the introduction of large third-party libraries, has good compatibility, and excellent performance:

You can add this JavaScript code in your website's public template file (for example/template/您的模板目录/bash.htmlor/template/您的模板目录/partial/footer.html)的</body>before the tag, or directly in the article detail page<script>tag:

<script>
document.addEventListener("DOMContentLoaded", function() {
    const lazyImages = document.querySelectorAll('img[data-src]');

    const imageObserver = new IntersectionObserver((entries, observer) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                const lazyImage = entry.target;
                lazyImage.src = lazyImage.dataset.src; // 将data-src的值赋给src
                lazyImage.removeAttribute('data-src'); // 移除data-src属性
                lazyImage.classList.add('fade-in'); // 可选:添加一个动画类
                observer.unobserve(lazyImage); // 停止观察已加载的图片
            }
        });
    }, {
        rootMargin: '0px 0px 50px 0px' // 可选:提前50px加载图片,避免用户看到图片加载过程
    });

    lazyImages.forEach(lazyImage => {
        imageObserver.observe(lazyImage);
    });
});
</script>
<style>
/* 可选:图片加载前的占位样式和加载动画 */
img[data-src] {
    opacity: 0; /* 加载前隐藏图片 */
    transition: opacity 0.5s ease-in-out; /* 过渡效果 */
    /* 可以添加一个背景色或低质量图片作为占位符 */
    min-height: 100px; /* 至少给图片一个高度,防止布局抖动 */
    background-color: #f0f0f0; /* 占位背景色 */
}
img.fade-in {
    opacity: 1; /* 加载后显示图片 */
}
</style>

This code will:

  1. Run after the DOM content is loaded.
  2. Find all elements withdata-srcproperties<img>.
  3. Create aIntersection ObserverInstance, this instance will monitor whether these images have entered the user's viewport.
  4. When the image enters the viewport (or according torootMarginThe set lead-in enters, it willdata-srccopy the value tosrcattribute, triggering the browser to load the image.
  5. After the image is loaded, it will removedata-srcthe attribute and stop observing the image.
  6. Optional CSS styles can provide a smooth transition effect, making the image load appear more natural.

Combined with AnQiCMS image optimization function

In addition to lazy loading, AnQiCMS also provides other powerful image optimization features, which, when used in conjunction with lazy loading, can bring about even greater performance improvements:

  • WebP image format conversion:In the AnQiCMS backend 'Content Settings', you can choose to enable WebP image format.After enabling, uploaded JPG, PNG and other images will be automatically converted to WebP format. WebP images are usually smaller in size and faster to load than JPG/PNG files of the same quality.
  • Automatically compress large images:Similarly in the "Content Settings", AnQiCMS supports automatically compressing large images to a specified width, which can further reduce the size of image files and speed up transmission speed.
  • Thumbnail processing:AnQiCMS can automatically generate thumbnails based on preset sizes, and using thumbnails instead of the original images in scenarios such as list pages can greatly reduce data volume.

By combining lazy loading with the built-in image optimization feature of AnQiCMS, your website will be able to present high-quality image content at a faster speed and with fewer resource consumption, providing visitors with a smooth and pleasant browsing experience.


Frequently Asked Questions (FAQ)

Q1: Why did the images still not implement lazy loading after setting in the AnQiCMS template?lazy="data-src"?A1: AnQiCMS'lazy="data-src"The parameter is just to<img>label'ssrcattribute is replaced withdata-srcThis is for,prepareLazy-loaded HTML structure. To truly implement

Related articles

How to enable Markdown editor in AnQiCMS and ensure that mathematical formulas and flowcharts are displayed correctly on the webpage?

AnQiCMS provides a flexible and diverse editing experience for content creators, and the introduction of the Markdown editor has made it even more convenient for many users who are familiar with this concise markup language.However, simply enabling the Markdown editor is not enough for content that requires special rendering, such as mathematical formulas and flowcharts.This article will provide a detailed guide on how to enable Markdown editor in AnQiCMS and ensure that your web page can correctly and beautifully display complex mathematical formulas and flowcharts.### One, Enable

2025-11-07

How to display the current page's TDK (Title, Description, Keywords) information in AnQiCMS template?

In website operation, the TDK (Title, Description, Keywords) information of the website plays a vital role.They are not only the key for search engines to understand the content of the page, but also a critical factor for users to decide whether to click on your website in the search results.A well-optimized TDK can significantly improve a website's ranking in search engines and attract more target users.AnQiCMS (AnQiCMS) is a content management system designed for SEO optimization, naturally providing strong and flexible support for TDK management

2025-11-07

How to set and display the pseudo-static URL structure of the AnQiCMS website?

AnQiCMS provides a flexible and powerful pseudostatic URL structure setting function in website operation, which is crucial for the SEO performance and user experience of the website.Static URL, as the name implies, makes the dynamic page link look like a simple and regular static file path, thus making it easier for search engines to crawl and for users to understand.Why is the use of pseudo-static URLs so important?Before delving into how to set up pseudo-statics in AnQiCMS, let's briefly review why it occupies such an important position in website operations: 1.

2025-11-07

How to format and display the article's publish timestamp in AnQiCMS templates?

In Anqi CMS, we all hope that visitors can clearly see the publication or update time of the articles.A clear and beautiful time format not only enhances the professionalism of the page but also optimizes the user experience.AnQi CMS with its flexible template engine makes it very simple to customize the display format of timestamps.Next, we will explore how to present the publishing time of articles accurately and elegantly in the AnQiCMS template.Understanding time data in AnQiCMS templates

2025-11-07

How to display single page content in AnQiCMS, such as the "About Us" or "Contact Us" page?

Displaying single-page content such as 'About Us' or 'Contact Us' in AnQiCMS is a very intuitive and flexible process.The system is designed to meet the needs of such static information display, through simple backend management and powerful template rendering capabilities, allowing you to easily create and beautify these important web pages. ### Create and Manage Single Page in the Back-end Firstly, all the content of single pages needs to be created and managed in the AnQiCMS back-end.

2025-11-07

How to display the friend link list on the AnQiCMS website?

Friend links are an indispensable part of website operation, as they not only promote communication and cooperation between websites, but also have a positive effect on SEO optimization.In AnQiCMS, displaying the friend link list is a simple and efficient process, allowing website administrators to easily provide visitors with more valuable external resources. ### Backend Management: Configure Your友情链接 Firstly, you need to configure the友情链接 in the backend of AnQiCMS in order to display it on the front page.

2025-11-07

How to generate and display breadcrumb navigation in the AnQiCMS template?

In website operation, a clear navigation structure is crucial for improving user experience and search engine optimization (SEO).Imagine if, when visitors delve deep into your website, there was a path guide to tell them 'You are here', wouldn't that make them feel at ease and convenient?This is the function of Breadcrumb Navigation.It is like breadcrumbs scattered in fairy tales, helping users easily backtrack in the website and understand the position of the current page in the overall website structure.

2025-11-07

How to display the unique field content according to a custom content model?

AnQi CMS with its powerful content management capabilities, especially the flexible content model, makes the organization of our website content simpler than ever before.When the standard content field cannot meet specific business needs, a custom content model and its unique fields emerge.How can you accurately call and display these unique custom field contents in the website front-end template?This article will detail the mysteries revealed for you. ### 1. Understanding the content model and custom fields of AnQi CMS One of the core strengths of AnQi CMS is its highly flexible content model

2025-11-07