How to use the lazy loading feature of images in single page content?

Calendar 👁️ 62

As an experienced AnQiCMS website operator, I am well aware of the importance of website performance for user experience and SEO.Lazy loading of images is an indispensable optimization method to improve website loading speed, especially in single-page content that contains a large number of images.AnQiCMS provides good support for image lazy loading at the content rendering level, allowing us to implement this feature through simple template configuration combined with front-end technology.

I will elaborate in detail on how to implement lazy loading of images in the single-page content of AnQiCMS.

Implement the lazy loading feature in the single-page content of AnQiCMS.

In the digital age, users have increasingly high expectations for web page loading speed.Especially for single-page content rich in images, such as the "About Us" page, product detail pages, or some event introduction pages, the size of the image files is often a major factor in slowing down page loading speed.Image lazy loading (Lazy Loading) technology has emerged, which delays loading images outside the viewport until the user scrolls to their location, thereby significantly improving the initial loading speed of the page, reducing bandwidth consumption, and optimizing the user experience.

AnQiCMS as an efficient content management system has provided a mechanism for image lazy loading during content output. We only need to configure it at the template level and add a small amount of frontend JavaScript code to easily achieve this feature.

Support for lazy loading of images with AnQiCMS content tags

Using AnQiCMS template enginearchiveDetailorpageDetailOutput content fields of tags such asContentwhen you use specific parameters to process image tags, it can adapt to the lazy loading mechanism. Specifically, when you uselazy="data-src"When a parameter is specified, AnQiCMS will automatically convert all<img>label'ssrcproperties todata-srcproperties while keeping the original onessrcAs the source address read by the lazy loading library. This is a key step in implementing image lazy loading.

Detailed steps for implementing image lazy loading

Step one: Prepare the single-page content template

Firstly, you need to determine the template file used for your single-page content. According to AnQiCMS's template conventions, a single page usually corresponds topage/detail.htmlorpage/{单页ID}.htmlWait for the files. If you have set a custom template for a specific single page, make sure to perform the operation in the corresponding template file.

Step two: Call the single-page content in the template and enable lazy loading properties

Use it in the single-page template file you choosepageDetailtag to get the single-pageContentfield. Be sure to add it when callinglazy="data-src"parameters, and use|safea filter to ensure that AnQiCMS can correctly handle image tags and output unescaped HTML content.

For example, your template code may look like this:

<div class="page-content">
    {% pageDetail pageContent with name="Content" lazy="data-src" %}
    {{ pageContent|safe }}
</div>

In this code block:

  • {% pageDetail pageContent with name="Content" lazy="data-src" %}Instruct AnQiCMS to get the content of the current page'sContentfield and assign it to a variablepageContent.lazy="data-src"The parameter tells CMS to output all<img>label'ssrcattribute is replaced withdata-src.
  • {{ pageContent|safe }}topageContentthe content of the variable safely to the page.|safeThe filter is crucial because it prevents the CMS from double-escaping HTML content, ensuring that image tags (including newly added ones) and attributes can be correctly parsed by the browser.data-srcattributes can be correctly parsed by the browser.

After this step, all image tags in your single-page content will be<img src="image.jpg">changes to<img data-src="image.jpg">.

Step 3: Introduce a front-end JavaScript library to implement lazy loading behavior

The AnQiCMS template processing mechanism has completed the backend data preparation, but the actual image lazy loading behavior needs to be implemented on the front end through JavaScript. You need to introduce a front-end image lazy loading library or write custom JavaScript code to listendata-srcProperty and load image.

Popularlylazysizes.jsFor example, the library is very lightweight and easy to use:

  1. IntroductionlazysizesLibrary:Before yourbase.htmlThe template file (or any public template file loaded before a single page) of<body>before the tag ends, or<head>within the tag, to introducelazysizes.js. You can introduce it via CDN:

    <script src="https://cdn.jsdelivr.net/npm/[email protected]/lazysizes.min.js" async=""></script>
    
  2. Adjust the image class name: lazysizesThe library defaults to searching for images withlazyloadthe class name, and transferring theirdata-srcattribute values tosrcthe attributes. Therefore, when editing content in the CMS backend, you also need to manually add images forlazyloadThe class. Alternatively, you can also customize JavaScript, to add this class to all images when the page loadsdata-srcAdd this class to the images.

    A more automated method is to add when inserting images if your content editor allows itclass="lazyload"Or, you can write a small JavaScript snippet that runs after the page loads to adddata-srcto all imageslazyloadClass:

    document.addEventListener('DOMContentLoaded', function() {
        const images = document.querySelectorAll('img[data-src]');
        images.forEach(img => {
            img.classList.add('lazyload');
        });
    });
    

    Combined with AnQiCMS'slazy="data-src"Output,lazysizesWhen images enter the viewport, automaticallydata-srcAssign the URL tosrcto load the image.

Step 4: CSS Style Assistance (optional but recommended)

To provide a better user experience, you can add some placeholder styles before the image loads. For example,lazyloadSet the minimum height or background color of the image to avoid layout shift (layout shift).

.lazyload:not([src]) {
    visibility: hidden; /* 在图片未加载前隐藏 */
}
img.lazyload {
    min-height: 200px; /* 示例:设置最小高度,防止布局抖动 */
    background-color: #f0f0f0; /* 示例:加载前显示灰色背景 */
    transition: opacity 0.3s ease-in-out; /* 平滑加载效果 */
    opacity: 0;
}
img.lazyload.ls-loaded { /* 当图片加载完成后由lazysizes添加的类 */
    opacity: 1;
}

Points to note

  • |safeThe filter is indispensable: When outputting content fields that contain HTML tags, it is imperative to use|safethe filter. If it is missing, the CMS may escape HTML tags, causingdata-srcproperties to be incorrectly identified.
  • Choose the appropriate front-end library:exceptlazysizes, there are many other excellent lazy loading libraries likeVanilla-lazyloador use nativeIntersection Observer API). Choose the library that best suits your project requirements and technology stack. Please note that different libraries have differentdata-*Property naming conventions may vary, you may need to adjustlazy="data-src"ofdata-srcto match the requirements of the library you choose.
  • Ensure that the JavaScript code is loaded correctly:Make sure your lazy-loaded JavaScript library or custom script is loaded and executed correctly on the page.Common issues include script path errors, scripts running before DOM elements causing the image to be unable to be found, etc.
  • SEO friendliness:Modern search engine crawlers can usually execute JavaScript and recognize lazy-loaded content.But for practice, ensure that your lazy loading implementation does not hinder search engines from crawling key image content.data-srcIt is usually SEO-friendly when combined with the correct HTML structure.

By following these steps, you can effectively implement lazy loading of images in the single-page content of AnQiCMS, thus providing your website visitors with a smoother and faster browsing experience.


Frequently Asked Questions (FAQ)

1. Why did I set it in the template?lazy="data-src", The image still loads immediately without lazy loading effect?

This situation usually occurs because you have only completed the configuration of the AnQiCMS template part, but have not introduced the corresponding JavaScript lazy loading library on the front-end, or the library introduced has failed to correctly identify your images. AnQiCMS'slazy="data-src"The function is simply to help you shiftsrcproperties todata-srcThe actual lazy loading behavior (i.e., listen to scroll events, shiftdata-srcthe content to assign tosrc) Needs to be implemented by the front-end JavaScript. Make sure you have included something likelazysizesThis is a front-end lazy loading library, and the library can find and process images on your page (for example, images withlazyloadClass name). Check your browser's developer tools to see if the image tag has indeed changed.<img data-src="...">And check for any JavaScript errors.

2. Does AnQiCMS have built-in JavaScript lazy loading for images, do I need to introduce an external JS library?

AnQiCMS's content management system does not come with built-in front-end JavaScript lazy loading functionality. AnQiCMS provides the convenience of backend rendering, which means it can output to the page according to your template configuration,<img>label'ssrcproperties todata-srcThis is for front-end lazy loading preparation. This means you still need to manually import a front-end JavaScript library (such aslazysizes.js/Vanilla-lazyloador use nativeIntersection Observer APIThe separation is responsible for the actual image monitoring and loading logic. This separation makes the system more flexible, allowing you to choose the most suitable frontend solution according to your needs.

3. I can use custom properties such asdata-*(for exampledata-original) instead ofdata-src?

AnQiCMS'archiveDetailandpageDetaillabel'slazyThe parameters are flexible, you can uselazy="data-original"or any other you wish to usedata-*How to specify the translation by attribute name

Related articles

How to determine if a single page exists in the template and display its content?

As an experienced security CMS website operator, I know that it is crucial to flexibly control the display of content in template development, especially for single-page content such as "About Us" and "Contact Us" that may require dynamic judgment and display.In actual operation, we often need to decide whether to render a block or link based on the existence of the page to ensure the accuracy of the website content and the user experience.Below, I will elaborate on how to determine if a single page exists in the Anqi CMS template and display its content.###

2025-11-06

How to retrieve the list of all single pages using the `pageList` tag and display it on the front end?

As a senior person who is deeply familiar with AnQiCMS (AnQiCMS) operation, I know that content is the core position in website construction.The single page acts as the cornerstone for carrying corporate core information, service introduction, contact information, and other static content. Its effective display is crucial for users to understand the website and the corporate image.This article will elaborate on how to use the built-in `pageList` tag of AnQiCMS to retrieve and flexibly display all single page content on the frontend.### Master the `pageList` tag to build a clear single-page navigation and display In AnQiCMS

2025-11-06

`pageDetail` tag can call which detailed information of a single page (such as ID, title, content)?

As an experienced enterprise CMS website operation person, I know that efficient content management is crucial for the success of the website.The single page is an important part of the website architecture, carrying core static information such as 'About Us', 'Contact Information', and 'Terms of Service'.The Anqi CMS provides a powerful `pageDetail` tag, allowing operators to flexibly call and display various detailed information on a single page.The `pageDetail` tag is a data call tool designed specifically for single-page content in the Anqi CMS template engine

2025-11-06

What happens if the specified single-page template file does not exist?

In AnQi CMS, the single-page template file plays a crucial role, responsible for defining the layout and style of independent pages such as 'About Us' and 'Contact Information'.Website operators usually specify specific template files for these single pages according to business needs to achieve personalized content display.However, if the specified single-page template file does not exist, it will directly affect the normal access and user experience of the page.

2025-11-06

How to obtain the SEO title and description of a single page through template tags?

As an experienced security CMS website operator, I am well aware of the key role that each page plays in search engine optimization, especially the SEO title and description.They are not only the first line of defense to attract users to click, but also an important signal to convey the core content of the page to search engines.AnQi CMS is well-versed in this, providing us with powerful and flexible template tags, allowing us to precisely control the SEO elements of each single page.

2025-11-06

How to correctly call the `Link` single page link in the template?

As an experienced security CMS website operator, I know that correctly calling content links in templates is crucial for website user experience and search engine optimization.The single page is a key part that carries static information such as 'About Us' and 'Contact Information', and the accurate calling of its links is an indispensable part of daily operation. I will elaborate in detail on how to correctly call single-page links in the Anqi CMS template.### Understanding Single Page Links in AnQi CMS In AnQi CMS, a single page (also known as a "page") exists independently of content models such as articles, products, and the like.

2025-11-06

Can the creation time or update time of a single page be retrieved and displayed?

In the operation practice of Anqi CMS, we often pay attention to the time information of the release and update of website content.This is crucial for search engine optimization (SEO) and for users to understand the timeliness of content.Whether the creation time or update time of a single page (Page) can be obtained and displayed, a detailed analysis based on the document provided by Anqi CMS can lead to a clear conclusion.The 'Page Management' feature of AnQi CMS is mainly used to create and manage independent static content pages, such as 'About Us', 'Contact Information', etc.

2025-11-06

How to call single page data from other sites in a multi-site environment?

As an experienced CMS website operation person, I am well aware of the core position of content in website operation.How to efficiently and flexibly call and manage content in a multi-site environment, especially for single-page data, is a real challenge for many operators.AnQi CMS relies on its powerful multi-site management capabilities to provide us with an elegant solution. ### Content Sharing Strategy in the Multi-site Environment of Anqi CMS From the outset, Anqi CMS has taken into account the needs of enterprises and content operation teams for multi-site management.

2025-11-06