In today's rich content web world, the importance of website loading speed for user experience and search engine optimization (SEO) is self-evident.Especially when a page contains a large number of images, how to effectively manage the loading of these images, and avoid the lag caused by loading all resources at once has become a focus of many website operators.The lazy loading (Lazy Load) technology is a powerful tool to solve this problem, allowing images to be loaded only when the user is about to see them, thereby significantly improving page performance.
AnQiCMS as a high-performance content management system, fully considers the efficiency of content presentation.Although it is built based on the Go language and inherently possesses the advantage of rapid response, it also provides a flexible mechanism to cooperate and realize the lazy loading effect.Here, let's discuss how to configure AnQiCMS to enable smooth lazy loading of images on the website.
Understanding AnQiCMS image processing and lazy loading mechanism
In AnQiCMS, content management and template rendering are the core links of image lazy loading. The system itself focuses on backend data processing and the flexible use of template tags, providing a key template tag parameter that allows us to lazy load images during rendering.srcProperty is converted to other custom properties (such asdata-src)。Picture lazy loading usually relies on front-end JavaScript libraries, which will assign custom properties (such asdata-src)to the value.srcattribute to trigger the image loading.
Therefore, to implement lazy loading in AnQiCMS, mainly two steps are required:
- Configure in the AnQiCMS template, set the image's
srcProperty is replaced with the custom attribute required for lazy loading. - Introduce a front-end JavaScript lazy loading library, responsible for listening to whether the image enters the visible area and executing the loading operation.
Detailed configuration steps
第一步:Optimize backend image settings (辅助但重要)
Before starting lazy loading, it is advisable to first check some image optimization settings in the AnQiCMS backend, which can further improve the efficiency of image loading. Go to the AnQiCMS backend and find the "Content Settings" under "Global Function Settings":
- whether to enable Webp image formatIf your website images are mainly in JPEG and PNG formats, enabling WebP conversion can significantly reduce image size and increase transmission speed.AnQiCMS supports automatic conversion to WebP format when uploading images, which is an important step for image optimization.
- whether to automatically compress large images:Turn on this feature and set a reasonable width (such as 800px), which can avoid uploading images of excessively large original size, thereby reducing file size.
These settings do not directly implement lazy loading, but they ensure that even if images need to be loaded, their file size is optimal, complementing the lazy loading technology.
Second step: Modify the template to support lazy loading attribute conversion
AnQiCMS uses a template engine syntax similar to Django. For the images you insert in the document content,archiveDetailLabel to render document details. To implement lazy loading for these images, we need to use theContentfield, utilizing thelazyparameter to specify the imagesrcproperty's alternative name.
Assuming your lazy loading JavaScript library expects images to be useddata-srcwith attributes instead ofsrcto store the actual image address, then in your article detail template file (usually{模型table}/detail.htmlIn the)or custom document template)find the tag that renders the document content, and make the following modifications:
{# 假设archiveContent变量存储了文档的内容 #}
{% archiveDetail archiveContent with name="Content" lazy="data-src" %}
{{archiveContent|safe}}
Here,lazy="data-src"Parameters tell the AnQiCMS template engine to renderarchiveContentof<img src="...">to be displayedsrcrename the property todata-srcwhilesrcThe property itself may be set to empty or a placeholder image (the specific behavior depends on the internal implementation of AnQiCMS, but the core is that the real URL is transferred).|safeThe filter is required to ensure that the HTML content is parsed correctly and not escaped.
For images in non-document content areas (such as list page thumbnails, category Banner images, etc.)
If your list page (such as){模型table}/list.html) is used directly in other templates{{item.Thumb}}/{{item.Logo}}Wait for the image to display, these images will not be applied automaticallylazyparameters. You need to apply them manuallysrcattribute todata-srcEnglish, and you can add a unified CSS class name so that the front-end JavaScript can identify and handle them.
For example, in a loop of document lists:
{% archiveList archives with type="page" limit="10" %}
{% for item in archives %}
<li>
<a href="{{item.Link}}">
<img data-src="{{item.Thumb}}" alt="{{item.Title}}" class="lazyload-image"> {# 手动改为data-src并添加类名 #}
</a>
<h5>{{item.Title}}</h5>
</li>
{% endfor %}
{% endarchiveList %}
Here, we add a class to all images that need lazy loadinglazyload-imagefor easy selection by JavaScript later.
Third step: Introduce the front-end JavaScript lazy loading library
The AnQiCMS template system is responsible for preparing image properties, but the actual lazy loading logic needs to be implemented by frontend JavaScript.You need to select a lightweight lazy loading library and introduce it into your template.Intersection ObserverAPI, you can use it to write simple lazy loading logic without relying on third-party libraries.
usually, you would place this JavaScript code in the common header file of the template (such asbase.html) of<head>within a tag (if you want to start observing as soon as possible) or</body>Label before (if you want to execute after the DOM is loaded).
The following is an example of usingIntersection ObserverA simple JavaScript example to implement lazy loading:
<script>
document.addEventListener("DOMContentLoaded", function() {
// 选择所有带有data-src属性的图片,以及带有lazyload-image类的图片
const lazyImages = document.querySelectorAll('img[data-src], .lazyload-image');
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; // 将data-src的值赋给src
lazyImage.removeAttribute('data-src'); // 移除data-src属性
lazyImage.classList.remove('lazyload-image'); // 移除辅助类名
lazyImageObserver.unobserve(lazyImage); // 停止观察已加载的图片
}
});
});
lazyImages.forEach(function(lazyImage) {
lazyImageObserver.observe(lazyImage);
});
} else {
// Fallback for older browsers (可选,此处简化为直接加载)
lazyImages.forEach(function(lazyImage) {
lazyImage.src = lazyImage.dataset.src;
lazyImage.removeAttribute('data-src');
lazyImage.classList.remove('lazyload-image');
});
}
});
</script>
This code will:
- Waiting for the page DOM content to load completely.
- Find all elements with
data-srcattributes<img>tag, as well as those manually addedlazyload-imageclass:<img>Label. - If the browser supports
Intersection Observer - When the image enters the visible area,
data-srctosrcthen removedata-srcproperties andlazyload-imagethe class, and stop observing the image. - for those that do not support
Intersection ObserverAn outdated browser, provides an alternative solution (in the example it is loaded directly, you can also use other compatibility libraries).
Test and verify
Complete the above configuration and you can open your website and verify it through the browser's developer tools:
- Open developer toolsIn Chrome, Firefox, and other browsers, press
F12to open the developer tools. - Switch to the "Network" tabThis will display all resources loaded on the page.
- Filter image resourcesIn the Network tab, select the 'Image' (Img) or 'Media' filter.
- Scroll page: Observe the loading status of image resources.You will find that only when the image is about to enter or has already entered your screen's visible area, the corresponding image file will appear in the network request list, rather than all being requested at the initial page load.
If everything is normal, the images on your AnQiCMS website have successfully achieved lazy loading effects.
Summary
Through the combination of AnQiCMS flexible template tags with front-end JavaScript, achieving lazy loading of images is not complex.This can not only effectively improve the loading speed and user experience of the website, reduce unnecessary bandwidth consumption, but also greatly benefit the website's SEO performance.lazy="data-src"The clever use and the配合 of frontend lazy loading JavaScript are the core of picture 'lazy loading'.
Common Questions (FAQ)
1. Why did the image load immediately in the AnQiCMS template when I setlazy="data-src"?
AnQiCMSlazyParameters are only responsible for tagging the imagesrcrename the property todata-srcetc., it does not