On your AnQiCMS website, optimizing image loading is a key step to enhance user experience and website performance, especially for articles with a large number of image content.Image lazy loading (Lazy Load) technology is a highly efficient solution that allows the page to load only the 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 loading time, save bandwidth, and improve the overall website response speed.
AnQiCMS as an enterprise-level content management system, fully understands the importance of performance optimization, and therefore has provided a very convenient way to implement lazy loading of images when outputting article content.Implement this feature mainly involves two steps: first, configure the content output method in the AnQiCMS template, and then integrate a simple JavaScript code on your website front-end to handle image loading logic.
第一步:In AnQiCMS template, configure image lazy loading
AnQiCMS uses 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.{模型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 done througharchiveDetailTag to gainContentfield. To support lazy loading of images, we need to addarchiveDetaila tag withlazyParameter.
The original output of the article content in your template might look like this:
{% archiveDetail articleContent with name="Content" %}
{{ articleContent|safe }}
To enable lazy loading, you just need toarchiveDetailtag.lazy="data-src"parameter, like this:
{% archiveDetail articleContent with name="Content" lazy="data-src" %}
{{ articleContent|safe }}
Here are thelazy="data-src"is to tell AnQiCMS that when it renders the article content of<img>do not use the attribute directly when labeling,srcProperties to load images, rather than placing the original URL in a nameddata-srccustom attribute. For example, a<img src="https://en.anqicms.com/uploads/image.webp" alt="示例图片">The image label, 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 HTML content contained in the variable is safe and should be output directly, rather than escaped. If missing|safeYou might see the image tag displayed instead of the actual image.
You can customize it according to your front-end lazy loading library requirements.data-srcReplace it with other custom attributes, such asdata-originalordata-image-srcis compatible with the JavaScript lazy loading library you choose. However,data-srcis a very common and recommended choice.
第二步:集成前端JavaScript懒加载逻辑
AnQiCMS完成模板渲染,将srcattribute in the content withdata-srcAfter that, the front-end JavaScript code needs to “read” thesedata-srcproperties, and load the image when it enters the user's viewportdata-srcthe value to reassign tosrc, thus triggering the actual loading of the image.
Here we provide a modern Web API-based solutionIntersection ObserverA lightweight solution that requires no large third-party libraries, has good compatibility and excellent performance:
You can add this JavaScript code to your website public template file (for example/template/您的模板目录/bash.htmlor/template/您的模板目录/partial/footer.html) of</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:
- Run after the DOM content is loaded.
- Find all elements with
data-srcattributes<img>Label. - Create a
Intersection ObserverInstance, this instance will monitor whether these images have entered the user's viewport. - When the image enters the viewport (or according to
rootMarginThe set anticipation enters), it will copydata-srcthe value tosrcthe attribute, thus triggering the browser to load the image. - After the image is loaded, it will remove
data-srcthe attribute and stop observing the image. - Optional CSS styles can provide a smooth transition effect, making the image loading appear more natural.
Combined with the image optimization feature of AnQiCMS
In addition to lazy loading, AnQiCMS also provides other powerful image optimization features that, when used in combination with lazy loading, can bring about even greater performance improvements: English
- WebP Image Format Conversion:In AnQiCMS backend "Content Settings", you can choose to enable WebP image format.After enabling, uploaded JPG, PNG, and other image files 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 the specified width, which can further reduce the size of the image file and speed up the transfer speed.
- Thumbnail processing:AnQiCMS can automatically generate thumbnails based on preset sizes, which can significantly reduce data volume in scenarios where the original image does not need to be displayed, such as on list pages.
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.
Common Questions and Answers (FAQ)
Q1: Why did the lazy loading effect of the image not take effect after setting in the AnQiCMS template?lazy="data-src"?A1: AnQiCMS'slazy="data-src"the parameter only sets<img>Tagssrcattribute in the content withdata-src, this is toprepareLazy loading HTML structure. To truly implement