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

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