How to enable lazy loading of images in article content to speed up page loading and improve user experience?

Calendar 78

In website operation, page loading speed and user experience are always the core concerns.Images are an important part of web content and often also a major factor affecting page loading speed.A high-definition large image can enhance the visual effect, but if too many images are not properly handled, it will slow down the website speed and make visitors hesitate.

Fortunately, Anqi CMS provides us with a very convenient lazy loading (Lazy Load) feature, which helps us effectively solve this problem.In simple terms, lazy loading of images means that images are not loaded all at once when the page is loaded, but rather they start loading when the user scrolls the page and the images are about to enter the visible area.This is like flipping through a thick book, you only flip through a few pages you are currently reading, not opening the whole book at once.

Why is image lazy loading so important?

The benefits of enabling lazy loading of images are multifaceted:

  1. Speed up the first page load time:The browser does not need to load all image resources at once, which reduces the initial number of requests and data transfer volume, allowing users to see the main content of the page faster.
  2. Save bandwidth resources:For users who may never scroll to the bottom of the page, neither their devices nor the server need to transfer image data that has not been viewed.
  3. Improve user experience:The page responds faster, users feel smoother while browsing the content, reducing the anxiety of waiting.
  4. Beneficial for SEO optimization:Search engines are increasingly emphasizing the page loading speed, faster website loading speed can help improve search rankings.

AnQi CMS is a system focused on providing an efficient, customizable content management solution, and pays attention to high concurrency, security, and scalability, naturally understands this, and provides built-in lazy loading support.

How does AnQi CMS support lazy loading of images?

In AnQi CMS, implementing lazy loading for images is actually very simple. You may have noticed carefully, when dealing with article content, the document detail tag of AnQi CMS (archiveDetail)Provided a very practicallazyparameter. This parameter is specifically used to handle content(Content)images in the field.

The document clearly states,Contentfield supports lazy loading of images, just need to uselazy="data-src"This label is enough. This means that when you output the article in the templateContentif you add thislazyparameter, the system will automatically convertContentall within<img>label'ssrcreplaces itsdata-srcProperty.

For example, an image that was originally<img src="https://en.anqicms.com/uploads/image.webp" alt="示例图片">The image, after passing throughlazy="data-src"After processing, it will become<img data-src="https://en.anqicms.com/uploads/image.webp" alt="示例图片">. At this time, the browser will not immediately load this image, but will wait for us to use JavaScript to determine whether the image has entered the visible area, and thendata-srcAssign the value againsrcto achieve lazy loading.

Manual operation: Enable image lazy loading

Below, we will step by step complete the enablement of lazy loading:

Step 1: Locate the template file

Generally, the display template of article content is located in a similar manner{模型table}/detail.htmlpath, for examplearticle/detail.htmlorproduct/detail.htmlIf you are not sure which file it is, you can check the corresponding classification or model's document template settings under the 'Content Management' -> 'Document Classification' or 'Content Model' in the background.

Find the template file used for the detail page of your article, for example, we takearticle/detail.htmlas an example.

Second step: ModifyarchiveDetailTag

Open this template file and find the content output section of the articlearchiveDetailLabel. It usually looks like this:

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

We need to add parameters to this label:lazy="data-src"Parameters, after modification, will become:

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

Here|safeThe filter is very important, it tells the template engine toarticleContentVariables are output as safe HTML content and not escaped. If this is missing, lazy loading may not workdata-srcthe attribute may not work properly.

After completing this step, all images in the article contentsrcThe properties have been converted todata-srcyou can directly use

Step 3: Introduce the lazy loading JavaScript library

merelysrcThe property todata-srcIt's not enough, we still need a JavaScript code to listen for page scrolling and move the value back todata-srcwhen the image enters the visible areasrcProperty.

You can choose a lightweight lazy loading library, such aslazysizes.jsOr write a simple script yourself. For demonstration, we provide one based on the native of modern browsersIntersection Observer APIA simple script, you can add it to the public header or footer template file of your website (for examplebase.html)的<script>within the</body>tag before, to ensure that the DOM elements have loaded:

<script>
document.addEventListener("DOMContentLoaded", function() {
    // 获取所有带有 data-src 属性的图片
    let 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;
                    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 older browsers (可选, 这里简化为直接加载)
        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>

Fourth step: CSS styles may be needed (optional, but recommended)

To avoid the page content 'jitter' (Layout Shift) when the image loads, it is recommended to set a fixed width and height for the image or use CSS to reserve the image position. For example, you can add a minimum height to the image:

img[data-src] {
    min-height: 100px; /* 根据实际图片比例调整 */
    display: block; /* 避免一些行内元素的默认行为 */
}

Or, when publishing articles, make sure the images are accompanied bywidthandheightProperty.

Combined with other optimization methods, the effect is better

The Anqi CMS also provides other practical functions in image processing, which can make the website performance even better when used with lazy loading. You can find them in the "Content Settings" panel on the backend:

  • Do you want to enable Webp image format:Enable this feature, and the uploaded JPG, PNG, and other images will be automatically converted to a smaller file size WebP format, further reducing the image size.
  • Whether to automatically compress large images:When the size of the image you upload is too large, the system can automatically compress it to the specified width, effectively saving storage space and loading time.
  • Thumbnail processing method and size:The website can automatically generate thumbnails of different sizes as needed by the frontend, ensuring that appropriate-sized images are loaded on list pages and other places.

By combining image lazy loading with these built-in image optimization features, your security CMS website will experience significant improvements in loading speed and user experience.

Frequently Asked Questions (FAQ)

Q1: I have followed the steps already inarchiveDetailtags.lazy="data-src", but the image seems to load immediately, why is that?

A1: The most common reason is that you may have forgotten to include the corresponding JavaScript lazy loading script in the website template, or the script may not be running correctly.lazy="data-src"Just to display the image'ssrcattribute todata-srcTo truly implement the "lazy" loading mechanism, JavaScript code is needed to listen to thesedata-srcWhen the image enters the user's visible area, then dynamically loaddata-srcAssign the value againsrcPlease check yourbase.htmlOr the related template file contains the correct JavaScript lazy loading script, and ensure that the script does not have syntax errors or is blocked from execution by other JS conflicts.

Q2: Enabling lazy loading of images will it have a negative impact on the SEO of the website??

A2: Just the opposite, modern search engines (especially Google) have a positive attitude towards lazy loading of images.Implementing lazy loading correctly usually has a positive impact on SEO.Search engines' crawlers can now typically execute JavaScript and recognizedata-srcProperties such as. Faster page loading speed, better user experience (Core Web Vitals metrics) are themselves important factors for SEO ranking.Just make sure that the lazy-loaded image content is still crawlable and indexable by search engines, and there are no JS errors that cause the image to fail to load, then there will be no problem.

Q3: Besides the images in the article content, can the other images on my website (such as banner images, thumbnails) also be lazy-loaded using this method?

A3:lazy="data-src"This parameter is specifically designed forarchiveDetailLabel outputContentThe image in the field is processed. For images in other locations on the website

Related articles

How to configure AnQiCMS to automatically convert uploaded images to WebP format for optimized display performance?

The loading speed of a website is one of the key factors in user experience and search engine optimization, and images, as an important part of web content, often occupy most of the time it takes to load a page.Convert images to more efficient formats like WebP, which can significantly reduce the size of image files, thereby improving the display performance of websites.AnQiCMS as a content management system that focuses on performance and user experience, is built with the feature of automatically converting images to WebP format.This article will give a detailed introduction on how to configure this feature in AnQiCMS, making your website images automatically optimized during upload

2025-11-08

How to embed Json-LD structured data in a page to enhance the rich media display of search engine results?

In today's highly competitive online environment, it is crucial to make your website content stand out in search engine results pages (SERP) to attract user clicks.And JSON-LD structured data is an important tool to achieve this goal.By embedding Json-LD in the page, you can provide clear information about the page content to search engines, thereby having the opportunity to display in search results in a richer form (such as star ratings, product prices, article thumbnails, etc.), which is what we commonly refer to as 'rich media results'

2025-11-08

Does AnQiCMS support generating and displaying canonical URLs (Canonical URL) to avoid duplicate content issues?

In website operation, duplicate content is undoubtedly a major challenge in Search Engine Optimization (SEO).Search engines tend to provide users with the most relevant and authoritative content. When they find the same or highly similar content under multiple URLs, they may feel confused, not knowing which version to index, which may scatter the ranking signals of the page and even affect the overall reputation of the website.For this issue, AnQiCMS provides a clear and practical solution, explicitly supporting the generation and display of canonical URLs.This means as a website operator

2025-11-08

How to dynamically set the Title, Keywords, and Description (TDK) information for each page?

In website operation, each page's Title (title), Keywords (keywords), and Description (description) information, which we commonly call TDK, plays a vital role.They are not only the key for search engines to understand page content, but also important factors to attract users to click.In AnQiCMS, dynamically setting this information for each page is much more efficient and flexible than you might imagine.How to make TDK settings efficient and convenient in AnQiCMS

2025-11-08

How to set and call the thumbnail of an article, category, or single page, and control its display size?

In website operation, images are not only an important part of content attractiveness, but also a key factor affecting page loading speed and user experience.Especially for articles, categories, or single-page content, an appropriate thumbnail can quickly catch the visitor's attention and guide them to click for more in-depth information.In Anqi CMS, setting and calling these thumbnails, and flexibly controlling their display size, is actually simpler and more efficient than imagined.### Easily manage thumbnails on the backend: Upload and intelligent extraction First, let's learn how to set thumbnails for your content on the Anqi CMS backend

2025-11-08

Can I set multiple Banner groups in AnQiCMS and display them at different positions separately?

In AnQiCMS, you can completely set up multiple Banner groups and flexibly display them in different positions according to the website layout.AnQiCMS provides a multi-dimensional way to manage and call these important visual elements to help you better organize website content and attract visitors.### One, the core concept of Banner management in AnQiCMS AnQiCMS demonstrates high flexibility and customization in Banner management

2025-11-08

How to display the user comment list on the article detail page and support

In website operation, the user comment feature on the article detail page is a key factor in enhancing user interaction and website activity.AnQiCMS (AnQiCMS) provides powerful and flexible comment management capabilities, allowing you to easily display comment lists on article detail pages, support user comment submissions, and even further enhance comment functions. ### 1. Preparation: Understanding the Comment Mechanism and Template Structure In Anqi CMS, each article can independently enable the comment function.When the user submits a comment on the article detail page, these comments will be associated with the corresponding article.To implement the display and submission of comments

2025-11-08

How to customize the display layout of the article detail page in AnQiCMS?

In AnQi CMS, the layout customization of the article detail page is a key factor in improving the user experience and display effect of the website.Benefiting from its flexible template mechanism, we can easily create unique article detail pages according to specific needs.Below, we will delve into the process of locating template files, core data calls, and how to use advanced features to achieve personalized layouts, among other aspects.### Understand the template working mechanism of AnQi CMS The template system of AnQi CMS is the foundation of its flexibility, it uses syntax similar to Django template engine

2025-11-08