How to implement the lazy loading display of image content in the article detail page to improve page loading speed?

In today's fast-paced online environment, website loading speed is a key factor in user experience and search engine ranking.For article detail pages containing a large number of images, optimizing image resources is particularly important.By implementing image lazy loading, we can significantly improve the initial loading speed of the page, allowing visitors to see the content faster and thus enjoy a better experience.

The AnQiCMS (AnQiCMS) takes full consideration of website performance optimization needs in its design, providing a concise and efficient way to achieve lazy loading of images on article detail pages.

Understand the working principle of image lazy loading

Before delving into the specific operations of the Safe 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 in the visible area of the user's current screen.When the user scrolls down the page, the images that are about to come into view will start loading.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.

The core method of implementing image lazy loading in the Anqi CMS

AutoCMS provides a mechanism for configuring image lazy loading directly in templates, which is mainly through the article detail page.Contentfields.

According to the AutoCMS template tag document, when you use tags in the template.archiveDetailLabel to display article content, can beContentfield.lazyProperty. The function of this property is to inform the system that images in the article content<img>tags)srcProperty is automatically replaced with the 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, it will obtain all the content of the current article.lazy="data-src"Is the key to implementing lazy loading. It will rename all attributes in the article content to<img>Tagssrcauto, to automatically renamedata-srcproperties.
  • {{ articleContent|safe }}:|safeThe filter is very important. Since the content of the article usually contains HTML tags (such as images, paragraphs, etc.), if you do not use|safeThese HTML tags will be escaped to plain text by the system, causing the page to display incorrectly.

After such settings, the image tags originally in the article content, such as<img src="https://en.anqicms.com/uploads/image1.jpg" alt="图片1">auto,在页面输出时就会变成auto<img data-src="https://en.anqicms.com/uploads/image1.jpg" alt="图片1">auto。此时,浏览器并不会立即加载这些图片,因为它们没有autosrcproperties.

Activate lazy loading effect: coordination with front-end JavaScript

Although the Anqi CMS helps us handle the pictures'srcThe attribute has been converted 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.data-srcThe value of the property is reassignedsrcThe property, thus triggering the image loading.

Here is an example that is widely supported by modern browsersIntersection Observer APIA JavaScript example for 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.html) or public footer, make sure it is loaded and executed on all required article detail pages.DOMContentLoadedIn the event listener, it is to ensure that the DOM is fully loaded before executing the script, to avoid the problem that the selector cannot find the element.

Multi-pronged approach: Combine with other optimization features of AnQi CMS

In addition to lazy loading images, Anqi CMS also provides a variety of image and website performance optimization features, which can achieve better results when used together:

  1. 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" features.The system will automatically process the image during upload, reduce the file size of the image, and further improve loading speed.
  2. Thumbnail size setting:For images in the article list page or a specific area, you can generate thumbnails of different sizes through the "Thumbnail Size" feature in "Content Settings" to avoid loading large images where they are not needed.
  3. Static cache:AnQi CMS supports static cache functionality. For articles with many images, enabling static cache can reduce server pressure and speed up page response time.

Through the image lazy loading configuration built into the Anqi CMS, combined with a simple piece of frontend JavaScript code, you can easily implement image lazy loading on article detail pages, significantly improving the website's access speed and user experience.This can not only leave a better impression of your website in users' minds, but also help improve its performance in search engines.

Common Questions (FAQ)

1. What is the impact of lazy loading on the SEO of a website?Images 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.These are all signals that search engines love: through lazy loading, the page loads faster, which can reduce the bounce rate and increase the user's stay time.At the same time, modern search engines (such as Google) can execute JavaScript, so they can "see" and index the content of images loaded through lazy loading.

2. How do I know if the images uploaded to the Anqi CMS backend have applied lazy loading?You can verify in two ways:

  • View the page source code:After the article detail page is loaded, right-click to view the page source code. If the image<imgTagssrcattribute has becomedata-srcattribute, it means that the security CMS has been processed correctly.
  • Browser Developer Tools:Open the developer tools (F12) of the browser, switch to the “Network” (network) tab, and filter image resources.Then scroll the page, observe whether the image resources start to load when you scroll near them.

3. How can I handle not using lazy loading for an image in the content of an article?[Currently] the 安企CMS[AnQi CMS]lazy="data-src"Properties will be handled uniformlyContentAll images in the field.If you have individual images that you want to load immediately, you need to slightly adjust the article content or template.<img src="your-image.jpg" class="no-lazyload" alt="xxx">and ensure that JavaScript lazy loading scripts will skip the fields withno-lazyloadThe image of the class name.This requires you to modify the provided JavaScript code to ignore these specific images.Contentfield output.