How to enable lazy loading of images in article content to speed up page loading and improve user experience?

In website operation, page loading speed and user experience are always the core concerns.The image is an important part of web page content and often also one of the main factors affecting page loading speed.An HD image can enhance the visual effect, but too many images without proper handling will slow down the website speed and deter visitors.

幸运的是,安企CMS为我们提供了非常便捷的图片懒加载(Lazy Load)功能,帮助我们有效解决这个问题。In simple terms, lazy loading of images means that images are not loaded all at once when the page is loaded, but rather begin to load when the user scrolls the page and the images are about to enter the visible area.This is like flipping through a thick book, you only turn the pages you are currently reading, rather than spreading out the whole book at once.

Why is image lazy loading so important?

The benefits of enabling lazy loading of images are multi-faceted:

  1. Accelerate the speed of the first page load:The browser does not need to load all image resources at once, reducing the number of initial requests and data transfer, allowing users to see the main content of the page faster.
  2. Save bandwidth resources:For users who may never scroll to the bottom of the page, neither the device nor the server needs to transfer image data that has not been viewed.
  3. Enhance user experience:The page responds faster, and users feel more smooth when browsing the content, reducing the anxiety of waiting.
  4. Beneficial for SEO optimization:Search engines are increasingly emphasizing the page loading speed, and a faster website loading speed helps improve search rankings.

auto

How does Anqi CMS support lazy loading of images?

In AnQi CMS, implementing lazy loading for images is actually very simple. You may have noticed, with careful attention, that when dealing with article content, the document detail tag of AnQi CMS, archiveDetail)provided a very practicallazyparameter. This parameter is specifically used to handle content(Content)images in the field.

The document explicitly states,Contentfield supports lazy loading of images, just need to uselazy="data-src"This label can be used. This means that when you output the article in the template.ContentIf you add this parameter.lazyto the system will automatically.Contentall in.<img>Tagssrcare replaced withdata-srcproperties.

For example, a photo that originally was<img src="https://en.anqicms.com/uploads/image.webp" alt="示例图片">The picture, afterlazy="data-src"After processing, it will become<img data-src="https://en.anqicms.com/uploads/image.webp" alt="示例图片">。此时,浏览器不会立即加载这张图片,而是等待我们通过 English 来判断图片是否进入了可视区域,再将data-srcthe value to reassign tosrcThus, lazy loading is achieved.

Manual operation: Enable image lazy loading

Next, we will step by step complete the enablement of lazy loading:

第一步:Locate the template file

Generally, the display template of article content is located in a similar manner{模型table}/detail.htmlThe path under, for examplearticle/detail.htmlorproduct/detail.html.If you are not sure which file it is, you can check the corresponding classification or model's 'Document Template' settings under 'Content Management' -> 'Document Classification' or 'Content Model' in the background.

Find the template file used for the article detail page you are using, for example, we takearticle/detail.htmlas an example.

Step 2: ModifyarchiveDetailtags

Open this template file, find the content output section of the article.archiveDetailLabel. It usually looks like this:

{%- archiveDetail articleContent with name="Content" %}
{{articleContent|safe}}

We need to add parameters to this label:lazy="data-src"Parameters, after modification, it will become:

{%- archiveDetail articleContent with name="Content" lazy="data-src" %}
{{articleContent|safe}}

Here are the|safeThe filter is very important, it tells the template engine toarticleContentVariables are output as safe HTML content rather than escaping. If this is missing, lazy loadingdata-srcattributes may not work properly.

Complete this step and all images in the article content will besrcthe attributes have been converted todata-src.

Step 3: Introduce the lazy loading JavaScript library

merely tosrcattribute todata-srcIt is not enough, we also need a piece of JavaScript code to listen for page scrolling, and when the image enters the visible area, setdata-srcthe value 'back to' srcproperties.

You can choose a lightweight lazy loading library, such aslazysizes.js, or write a simple script yourself. For demonstration, we provide one based on the native browser of modernIntersection Observer APIThe simple script, you can add it to the public header or footer template file of your website (for examplebase.html) of<script>tag, it is recommended to place</body>tag before, to ensure that the DOM elements have been loaded:

<script>
document.addEventListener("DOMContentLoaded", function() {
    // 获取所有带有 data-src 属性的图片
    let lazyImages = [].slice.call(document.querySelectorAll("img[data-src]"));

    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;
                    if (lazyImage.dataset.srcset) {
                        lazyImage.srcset = lazyImage.dataset.srcset;
                    }
                    lazyImage.removeAttribute("data-src");
                    lazyImage.removeAttribute("data-srcset");
                    lazyImageObserver.unobserve(lazyImage);
                }
            });
        });

        lazyImages.forEach(function(lazyImage) {
            lazyImageObserver.observe(lazyImage);
        });
    } else {
        // Fallback for older browsers (可选, 这里简化为直接加载)
        lazyImages.forEach(function(lazyImage) {
            lazyImage.src = lazyImage.dataset.src;
            if (lazyImage.dataset.srcset) {
                lazyImage.srcset = lazyImage.dataset.srcset;
            }
            lazyImage.removeAttribute("data-src");
            lazyImage.removeAttribute("data-srcset");
        });
    }
});
</script>

Fourth step: CSS styles that may be needed (optional, but recommended)

To avoid the page content 'jitter' (Layout Shift) when the image loads, it is recommended to set a fixed width and height for the image, or use CSS to reserve the image position. For example, you can add a minimum height to the image:

img[data-src] {
    min-height: 100px; /* 根据实际图片比例调整 */
    display: block; /* 避免一些行内元素的默认行为 */
}

or, make sure the image is accompanied by when posting articleswidthandheightproperties.

combined with other optimization methods, the effect is better

The 'AnQi CMS' provides other practical functions in image processing, which, when used in conjunction with lazy loading, can enhance the website performance to a higher level. You can find them in the 'Content Settings' on the backend:

  • Whether to start Webp image format:Enable this option, and uploaded JPG, PNG, and other image files will be automatically converted to a smaller WebP format, further reducing the size of the images.
  • Whether to automatically compress large images:When the size of the image you upload is too large, the system can automatically compress it to the specified width, effectively saving storage space and loading time.
  • Thumbnail processing methods and dimensions:The website can automatically generate thumbnails of different sizes according to the needs of the front-end, ensuring that the appropriate size images are loaded on list pages and other places.

Through combining image lazy loading with these built-in image optimization features, your safety CMS website will experience a significant improvement in loading speed and user experience.

Common Questions (FAQ)

Q1: I have followed the steps inarchiveDetail标签中添加了lazy="data-src"But the image seems to load immediately, why is that?

A1: The most common reason is that you may have forgotten to include the corresponding JavaScript lazy loading script in the website template, or the script is not running correctly.lazy="data-src"Just changing the image'ssrcchange the properties todata-srcThe mechanism to truly implement "lazy" loading requires JavaScript code to listen to thesedata-srcWhen the image enters the user's visible area, then dynamically loaddata-srcthe value to reassign tosrcPlease check yourbase.htmlOr does the template file include the correct JavaScript lazy loading script, and ensure that the script does not have syntax errors or is blocked from execution by other JS conflicts.

Q2: Enabling image lazy loading will it have a negative impact on the website's SEO?

A2: Exactly the opposite, modern search engines (especially Google) have a positive attitude towards lazy loading of images.Correctly implemented lazy loading usually has a positive impact on SEO.data-srcEnglish.Faster page loading speed, better user experience (Core Web Vitals metrics) are important factors for SEO ranking.Ensure that the lazy-loaded image content is still crawlable and indexable by search engines, and there are no JS errors that cause the image to fail to load, then there is no problem.

Q3: Can the other images on my website (such as banner images, thumbnails) also be lazy-loaded using this method?

A3:lazy="data-src"This parameter is specifically designed forarchiveDetailtag outputContentThe image in the field is processed. For other images in the website.