How to implement lazy loading display effect of images in AnQi CMS article content?

In website operation, image loading speed is crucial for user experience and search engine optimization (SEO).Especially when an article contains a large number of images, loading all the images at once will significantly increase the page loading time, consume user traffic, and may cause users to leave prematurely.At this moment, the Lazy Load image technology can fully display its capabilities.

The core idea of lazy loading is to start loading images only when they are about to enter the user's visible area, rather than loading all of them at the initial page load.This can effectively reduce the time and resources required for the first page load, improve the response speed and overall performance of the website, thereby improving the user experience and helping with SEO performance.

Why implement lazy loading in AnQi CMS article content?

AnQiCMS as a content management system that focuses on performance, user experience, and SEO optimization, naturally provides convenience for such optimization.The powerful content management and flexible template mechanism makes it easy to introduce lazy loading effects in the content of article detail pages.Imagine, when a user opens a long article, if all the images are loaded silently in the background, the article will appear faster in front of them, and the loading of the images will be on demand, which will undoubtedly improve user satisfaction.

Core implementation: utilizingarchiveDetaillabel'slazyParameter

The rendering of article content in the AnQiCMS template system is mainly achieved througharchiveDetailtags. To implement lazy loading, we can cleverly utilizearchiveDetailin the labellazyParameter.

archiveDetailThe tag is used to obtain detailed document data, whereContentthe field contains the full HTML content of the article. AnQiCMS provides a very practicallazyparameter that can be directly modifiedContentin the field<img>label'ssrcis a custom lazy loading attribute.

The specific usage is as follows:

In your article detail template (usually{模型table}/detail.htmlor find the part of the code that renders the article content in the custom document template and addlazyparameters:

{# 默认用法,自动获取当前页面文档 #}
<div>文档内容:{% archiveDetail with name="Content" %}</div>

{# 添加 lazyload 替换 #}
<div>文档内容:{% archiveDetail archiveContent with name="Content" lazy="data-src" %}{{archiveContent|safe}}</div>

In this example,lazy="data-src"tell AnQiCMS's template engine to render all<img>label'ssrcattribute is replaced withdata-srcAttribute. For example, an original image tag<img src="path/to/image.jpg">After going throughlazy="data-src"After processing, it will become<img data-src="path/to/image.jpg">.

You can also set the parameter value to another attribute name according to the requirements of the front-end lazy loading library you choose, such aslazyFor example, you can set the parameter value to another attribute name, such aslazy="data-original"orlazy="data-ll-src"The key is, this property name must be consistent with the one you will use in the JavaScript lazy loading library on the front-end.

Front-end collaboration: JavaScript script enables lazy loading

Modified HTML attributes require a JavaScript code snippet to \data-srcAssign the actual image address to thesrcto trigger the image loading.

Although AnQiCMS itself does not integrate lazy loading JavaScript scripts, there are many lightweight and efficient lazy loading libraries available on the market, or you can also write a simple script yourself.

Here is a based onIntersection Observer APIofconceptualJavaScript code example, you can integrate it into your website template (for example, place it inbase.htmlthe file</body>Before the tag, or on a specific detail page template<script>In the tag):

// 选择所有带有 data-src 属性的图片(即需要懒加载的图片)
const lazyImages = document.querySelectorAll('img[data-src]');

// 检查浏览器是否支持 Intersection Observer
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.classList.add('loaded'); // 可选:添加加载完成的样式
                lazyImageObserver.unobserve(lazyImage); // 停止观察这张图片
            }
        });
    }, {
        rootMargin: '0px 0px 50px 0px' // 可选:提前50px加载,优化用户体验
    });

    lazyImages.forEach(function(lazyImage) {
        lazyImageObserver.observe(lazyImage); // 观察每一张需要懒加载的图片
    });
} else {
    // 浏览器不支持 Intersection Observer 时的备用方案
    // 例如,直接加载所有图片,或者使用其他基于滚动事件的方案
    lazyImages.forEach(function(lazyImage) {
        lazyImage.src = lazyImage.dataset.src;
    });
}

How to deploy this JavaScript code:

  1. Save the script:Save the above (or the lazy loading library of your choice) JavaScript code as a.jsa file, for examplelazyload.jsand upload it to your template static resources directory (usually)/public/static/您的模板目录/js/)
  2. to include the script:Before yourbase.htmlOr in the article detail page template, use<script>the tag to introduce this file. Usually, to avoid blocking the page rendering, it is recommended to place it</body>before the tag.
    
    <script src="{% system with name="TemplateUrl" %}/js/lazyload.js"></script>
    

Overview of the actual operation steps:

  1. Modify the template file:Open yourarchiveDetailarticle detail page template for the tag (such as/template/default/archive/detail.html),to{% archiveDetail with name="Content" %}is modified to{% archiveDetail archiveContent with name="Content" lazy="data-src" %}{{archiveContent|safe}}.
  2. introduce JavaScript script:Save the selected lazy-loaded JavaScript code (such as the conceptual code above or third-party libraries) as.jsa file and upload it to the website's static resources directory. Then,base.htmlthe file</body>Before the tag, introduce this script.
  3. Refresh the cache:In AnQiCMS backend, click 'Update Cache' to ensure that template file modifications and the new JavaScript file are loaded correctly.
  4. Test:Visit your article detail page, scroll the page, and observe whether the images are loaded only when they are about to enter the visible area.You can use the browser developer tools (F12) Network tab to filter image resources to verify the lazy loading effect.

Note:

  • Placeholder image:For a better user experience, you can add to<img>In the tag, set a lightweight placeholder image (loading.gif or solid color image) so that there is no large blank space before the image is loaded.srcproperties (pointing to the placeholder) and adddata-src(Point to the real image to implement. However, AnQiCMS's)lazyparameters will be replaced directlysrcIf you need placeholders, you may need to make more precise controls on the CSS or JavaScript level, such as displaying a background color before the image is loaded orloadingthe icon.
  • SEO friendliness:Modern search engines (such as Google) have crawlers that can execute JavaScript, so correctly implemented lazy loading is friendly to SEO. They can readdata-srcProperties and understand that this is a lazy-loaded image. However, to be on the safe side, it is always recommended tonoscriptprovide alternative content in the tag or offer text when the image fails to loadalt.
  • Adapt for mobile:Lazy loading is especially important for mobile devices, as it can significantly reduce mobile data traffic consumption and page loading time. It is essential to test on different mobile devices.
  • Progressive image loading:Combine the 'Content Settings' provided by AnQiCMS, such as 'Enable Webp Image Format' and 'Automatically Compress Large Images', to further optimize image loading performance, achieve progressive loading (that is, load low-quality images first, then high-quality images), and provide a smoother visual experience.

By following the above method, you can effectively implement lazy loading of images in AnQiCMS article content, bringing faster loading speed and a better user experience to your website.


Frequently Asked Questions (FAQ)

Q1: I have already set uparchiveDetaillabel'slazyParameter, why are the images still loading all at once when the page is opened?A1:lazyThe parameter is used to change the imagesrcattribute todata-srcCustom attributes, this is just a change at the HTML level. To truly implement lazy loading of images, you also need to introduce JavaScript scripts on the front end to listen for the attributes withdata-srcThe image of the property and assigndata-srcthe value back tosrcProperty. If the front-end JavaScript script is not introduced or properly configured, the lazy loading effect will not take effect.

Q2: Do image lazy loading have a negative impact on my website's SEO? Can search engines crawl images that are lazy loaded?A2: For modern search engines, especially Google, they have JavaScript rendering capabilities and can usually correctly crawl and index images loaded through lazy loading technology.Therefore, correctly implemented lazy loading usually does not have a negative impact on SEO, and may even indirectly help SEO by improving page loading speed.data-srcThe attribute contains the real URL of the image and the image is also configured with meaningfulalt.

Q3: Can I use attributes other thandata-srcto achieve lazy loading?A3: Perfectly okay.archiveDetaillabel'slazyThe parameter is very flexible, you can set it to any attribute name you need according to the requirements of the front-end lazy loading JavaScript library you choose, for examplelazy="data-original"/lazy="data-lazy-src"Wait. As long as your front-end JavaScript script can recognize and handle this custom attribute, lazy loading will work normally.