In today's fast-paced online environment, website loading speed is a key factor in user experience and search engine rankings.For an article detail page with a large number of images, optimizing image resources is particularly important.By implementing lazy loading of images, we can significantly improve the initial loading speed of the page, allowing visitors to see the content faster and thus providing a better experience.
AnQiCMS was designed with full consideration of website performance optimization needs, providing a simple and efficient way to achieve image lazy loading on article detail pages.
Understand the working principle of lazy loading images
Before delving into the specific operations of AnQi CMS, let's briefly understand image lazy loading.It does not load all the images on the page at once, but only loads the images within the visible area of the user's current screen.When the user scrolls down the page, the images that are about to enter the field of view will start to load.This "lazy loading" mechanism can greatly reduce the amount of data that needs to be processed when the page is first loaded, thereby speeding up the display speed of the page.
Implement the core method of lazy loading images in Anqi CMS
The AnQi CMS provides a mechanism to configure image lazy loading directly in the template, which is mainly through the article detail page.Contentto implement the field.
According to the AnQi CMS template tag documentation, when you use the template tags in the template,archiveDetailTo display the article content, you can use aContentAdd a fieldlazyattribute. The purpose of this attribute is to inform the system that images in the article content should be<img>tag'ssrcThe property is automatically replaced with a specified custom property, for exampledata-src.
The specific template code example is as follows:
{# 获取文章详情内容,并启用图片懒加载功能 #}
<div>
{% archiveDetail articleContent with name="Content" lazy="data-src" %}
{{ articleContent|safe }}
</div>
In this code block:
{% archiveDetail articleContent with name="Content" lazy="data-src" %}This is the document detail tag of AnQi CMS, which retrieves all the content of the current article. Among whichlazy="data-src"is the key to lazy loading. It will take all the content in the article.<img>label'ssrcProperties, automatically renamed todata-srcProperty.{{ articleContent|safe }}:|safeThe filter is very important. Since the content of the article usually contains HTML tags (such as images, paragraphs, etc.), if not using|safeThese HTML tags will be escaped by the system as plain text, causing the page to display incorrectly.
After such settings, the original image tags in the article content, such as<img src="https://en.anqicms.com/uploads/image1.jpg" alt="图片1">, it will become when displayed on the page<img data-src="https://en.anqicms.com/uploads/image1.jpg" alt="图片1">. At this point, the browser will not load these images immediately because they do not havesrcProperty.
Enable lazy loading effect: cooperation with front-end JavaScript
Although AnQi CMS helps us with the image'ssrcattribute conversion todata-srcBut to truly implement 'lazy loading', a little front-end JavaScript code is needed to cooperate. This JavaScript code will monitor which images are about to enter the user's viewport and load them when they become visible, and thendata-srcAssigning the value of the propertysrcto trigger the image loading.
Here is an example supported by modern browsersIntersection Observer APIA JavaScript example of implementing lazy loading:
document.addEventListener("DOMContentLoaded", function() {
// 检查浏览器是否支持 Intersection Observer API
if ("IntersectionObserver" in window) {
let lazyImages = document.querySelectorAll("img[data-src]"); // 选中所有带有 data-src 属性的图片
let imageObserver = 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 属性,避免重复处理
imageObserver.unobserve(lazyImage); // 停止观察已加载的图片
}
});
});
lazyImages.forEach(function(lazyImage) {
imageObserver.observe(lazyImage); // 观察每一张懒加载图片
});
} else {
// 对于不支持 Intersection Observer 的旧版浏览器,可以提供一个简单的降级方案
// 例如,直接加载所有带有 data-src 的图片,确保内容可用
let lazyImages = document.querySelectorAll("img[data-src]");
lazyImages.forEach(function(lazyImage) {
lazyImage.src = lazyImage.dataset.src;
lazyImage.removeAttribute('data-src');
});
}
});
You can place this JavaScript code in the public header of the website template (bash.htmlOr the common footer, make sure it is loaded and executed on all article detail pages that require lazy loading. PlaceDOMContentLoadedWithin the event listener, it is to ensure that the DOM is fully loaded before executing the script, to avoid the problem of selectors not being able to find elements.
A multi-pronged approach: Combine Anqi CMS other optimization features
In addition to lazy loading images, Anqi CMS also provides a variety of image and website performance optimization features that can be used together to achieve better results:
- Automatic image compression and WebP conversion:In the background "Content Settings", you can enable the "Whether to automatically compress large images" and "Whether to start Webp image format" functions.The system will automatically process the image when it is uploaded, reduce the file size of the image, and further improve loading speed.
- Thumbnail size setting:For images on the article list page or specific areas, you can use the "Thumbnail Size" feature in "Content Settings" to generate thumbnails of different sizes, avoiding loading large images where they are not needed.
- Static cache:The Anqi CMS supports static caching functionality. Enabling static caching for pages with many images can reduce server pressure and speed up page response time.
By using the built-in image lazy loading configuration of AnQi CMS, along with a simple piece of frontend JavaScript code, you can easily implement image lazy loading on the article detail page, significantly improving the website's access speed and user experience.This can leave a better impression of your website in the minds of users, and also help improve its performance in search engines.
Frequently Asked Questions (FAQ)
1. How does lazy loading of images affect the SEO of a website?Image lazy loading has a positive impact on SEO. Search engines are increasingly emphasizing user experience, and page loading speed is one of the core indicators of user experience.By lazy loading, the page loads faster, which can reduce the bounce rate and improve user stay time, all of which are signals favored by search engines.At the same time, modern search engines (such as Google) can execute JavaScript, so they can "see" and index the image content loaded through lazy loading.
2. How do I know if the images uploaded to the Anqicms backend have applied lazy loading?You can verify in two ways:
- View the page source:After the article detail page is loaded, right-click to view the page source code. If the image
<imglabel'ssrcattribute has becomedata-srcattribute, it means that Anqie CMS has been processed correctly. - Browser Developer Tools: Open the browser's developer tools (F12), switch to the "Network" tab, and filter image resources.Then scroll the page and observe whether the image resources start to load when you scroll near them.
3. How can I handle a picture not using lazy loading in the article content?The current Anqi CMSlazy="data-src"properties will be processed uniformlyContentAll images in the field. If you have any images you want to load immediately, you need to adjust the content of the article or template slightly.A common method is to not directly insert the image when editing an article, but to insert it manually in text mode<img src="your-image.jpg" class="no-lazyload" alt="xxx">Ensure that the JavaScript lazy loading script skips the one withno-lazyloadThe image of the class. But this requires you to modify the provided JavaScript code to ignore these specific images.Or, you can call the image separately in the template, without passing it throughContentfield output.