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:
Introduction
lazysizesLibrary: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>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 it
class="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's
lazy="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:except
lazysizes, 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