How can AnQi CMS enable lazy loading display for images in document content?

In modern network environments, the loading speed of a website is one of the key factors affecting user experience and search engine rankings.When a web page contains a large number of images, these images often become the 'culprits' that slow down the loading speed.Imagine a user opening a page, even if they haven't scrolled to the bottom of the page, the browser has already started downloading all the images. This undoubtedly consumes valuable bandwidth and processing resources, leading to slow page response.

To address this pain point, the Lazy Loading (Lazy Loading) technology emerged.It does not load all the images on the page at once, but only loads those that enter or are about to enter the visible area based on the user's scrolling behavior.This makes the page load faster on the first load, significantly reduces resource consumption, and improves the user experience.

The AnQi CMS took full consideration of content optimization needs from the beginning of its design, not only pursuing high performance in system architecture, but also providing a convenient lazy loading implementation for image content.For images in document content (such as articles, product details, etc.), AnQi CMS can flexibly configure images to support lazy loading through its powerful template engine.

The core secret of implementing image lazy loading

In AnQi CMS, lazy loading of document content images is mainly achieved by modifying the tags used to display article details. The key is toarchiveDetailTags, especially when you need to display the article'sContentfield. The document content field itself supports a parameter namedlazywhich is the core of implementing lazy loading of images.

In simple terms, when you use it in a templatearchiveDetailyou can use tags to retrieve and render document content, and you can add it inContentthe field calllazy="data-src"this attribute.lazyThe attribute will indicate that the Anqie CMS template engine will render HTML, by<img>label'ssrcattribute is replaced withdata-src(or any other attribute name you define), while the actual image path will be stored in thisdata-srcproperties. For example, originally<img src="path/to/image.jpg">will be rendered as<img data-src="path/to/image.jpg">and usually does not havesrcproperties (orsrcproperties point to a placeholder).

Implement step by step: make the document images move

To implement lazy loading for images in the document content on your Anqi CMS website, the following steps are usually required:

  1. Prepare the frontend lazy loading libraryImage lazy loading usually requires the help of a JavaScript library to complete. There are many lightweight and efficient lazy loading libraries available, such asvanilla-lazyload/lozad.jsorlazysizes. They work in the same way, all of them listen to the page's scroll event, when the image enters the visible area, it willdata-srcAssign the actual image address to thesrcAttribute, thus triggering image loading.

    You need to choose a frontend lazy loading library you like and download its file (usually.jsand.cssfile) to the static resource directory of your website, such as/public/static/jsor/public/static/css.

  2. modify the template file to enablelazypropertyFind the template file used for the document detail page. According to the Anqi CMS template convention, it is usuallytemplate/{你的模板目录}/{模型table}/detail.htmlOr a custom document template file (such asarchive/detail.html)

    In this template file, you will find the tags used to display article contentarchiveDetailThe original code may look like this:

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

    To enable lazy loading, you need toarchiveDetaila tag toContentadd a fieldlazyParameter. Assuming the front-end lazy loading library you choose expects images to be useddata-srcattribute to indicate lazy loading images, then you can modify it like this:

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

    Herelazy="data-src"will tell the Anqi CMS template engine to renderarticleContentall variables<img>When labeling, theirsrcproperties are modified to the one you specifydata-src.|safeThe filter is indispensable, it ensures that the HTML content is parsed and displayed correctly, rather than being escaped into plain text.

  3. Introduce and initialize the front-end lazy loading libraryAfter completing the template modification, you still need to introduce and initialize the front-end lazy loading library you choose in the public header or footer of the website. This is usually intemplate/{你的模板目录}/bash.htmlorbase.htmlPerforming in the file.

    In</body>Before the tag, introduce your JavaScript file and initialize it according to the library's documentation. Tovanilla-lazyloadfor example, you may need to add similar code to the following:

    <script src="{% system with name="TemplateUrl" %}/js/lazyload.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            // 初始化 LazyLoad,并指定data-src作为懒加载属性
            var lazyLoadInstance = new LazyLoad({
                elements_selector: "img[data-src]", // 选择所有带有data-src属性的图片
                // 其他配置项,例如加载时的占位图等
            });
        });
    </script>
    

    Please write the initialization code according to the documentation of the lazy loading library you are actually using and make sureelements_selectorthe value matches thearchiveDetailas set in the taglazyproperty name you are using.

Benefits of lazy loading: more than just speed

The benefits of implementing lazy loading for images are multifaceted:

  • Improve page loading speedWhen the user opens the page, only the images visible on the first screen need to be loaded, greatly shortening the waiting time.
  • Save bandwidth resources: For the unscrollable area of the page, images are not loaded, reducing the traffic consumption of the server and the user.
  • Optimize search engine rankings: Faster page loading speed is an important ranking factor for search engines like Google, which helps improve the SEO performance of a website.
  • Improve user experienceA responsive website makes users happier, reduces the bounce rate, and improves the overall interactivity of the site.

Tip: Picture optimization tips.

In addition to lazy loading, Anqi CMS also provides other image optimization features in the content settings, which can work with lazy loading to bring a more comprehensive performance improvement to your website:

  • Enabled WebP image formatConvert uploaded JPG, PNG images to a smaller WebP format automatically, further reducing the size of the image file.
  • Automatically Compress Large Image:Automatically compress images that are too large in size, ensuring both display quality and saving storage space.
  • Thumbnail Processing MethodFlexiblely set the thumbnail generation method and size to ensure that small-sized images are loaded on list pages, recommendation slots, and other scenarios.

These features work together to allow your Anqin CMS website to achieve an excellent balance in content presentation and performance.


Frequently Asked Questions (FAQ)

1. I have already set up according to the steps.lazy="data-src"Also introduced the lazy loading JS library, why is the image still not lazy loading?This could be due to several reasons:

  • The JS library was not initialized correctlyPlease carefully check your frontend JS code, make sure the lazy loading library is correctly introduced, and the initialization function is called. Pay special attention.elements_selectorWhether the configuration matchesdata-srcthe attribute.
  • HTML rendering issuesCheck the browser developer tools to see if the image tag has really been rendered as<img data-src="xxx">this form. If it is still<img src="xxx">That may be because the template file was not updated correctly or the template cache of AnQi CMS was not cleared, please try to update the cache.
  • CSS style conflict: Some CSS properties such asdisplay: none;It may interfere with the lazy loading library's judgment of image visibility.

2. Of Anqi CMS'slazyThe attribute can be set asdata-originalOr can it be called by another name?Yes, it can be of Anqi CMS'slazyThe parameter is designed to be very flexible, the document clearly states that it can be usedlazy="{定义的src名}". This means you can set it according to the requirements of the frontend lazy loading library you chooselazy="data-original"/lazy="data-src-alt"Any name. But please make sure that the name you set in the template.lazyThe property name is consistent with the one initialized by the front-end JS library.elements_selectorConfigure the property name.

3. Does lazy loading of images have a negative impact on a website's SEO?Under normal circumstances, correctly implemented image lazy loading ispositive for SEO.. Search engines (especially Google) are already able to well crawl and index images using lazy loading.Faster page loading speed is itself an important SEO ranking factor.However, there are a few points to note:

  • Ensuredata-srcOr similar properties contain clickable image URLs, not empty.
  • Avoid overly aggressive lazy loading strategies, which means that images start loading long before the user scrolls, which may cause images to appear only when the user actually needs them, affecting user experience.
  • Add meaningfulaltattributes, which helps search engines understand the content of the image. Anqi CMS supports setting the Alt attribute when uploading images.