How to implement lazy loading (Lazyload) for images in the front-end to optimize page performance?

For AnQiCMS users, the system has provided a very convenient mechanism for implementing lazy loading of images in article content. In the template tags of AnQiCMS, when we usearchiveDetailTags to output the detailed content of the article (Content) can include a special parameter:lazy="data-src". This feature means that AnQiCMS will display images when rendering article content,<img>TagssrcProperty automatically replaced withdata-src. For example, a picture tag originally shaped like<img src="image.jpg" />will be transformed into<img data-src="image.jpg" />This is a very critical server-side preparation step, which provides identification and operation targets for the front-end lazy loading script.

To make this preprocessing effective, you usually need to do it in the template file, for example in the template for displaying article details (usually{模型table}/detail.htmlor similar files) to ensurearchiveDetailtags are used in the outputContentwhen displayinglazy="data-src"Parameters. Specific code examples are:{% archiveDetail articleContent with name="Content" lazy="data-src" %}{{articleContent|safe}}Here,articleContentis the name of the variable you define,name="Content"specified the field of the article content to be output,lazy="data-src"then indicates the system to perform lazy loading property conversion.

Completed the backend preparation of AnQiCMS, the next step is to introduce a frontend JavaScript lazy loading library to identify these withdata-srcThe image of the property, and when they enter the user's viewport,data-srcthe value to reassign tosrctriggering the actual loading of the image. There are many excellent lazy loading libraries available, such asvanilla-lazyload/lazysizesor you can use the built-in modern browser.Intersection Observer APIImplement it yourself.

Generally, you will find the public template files of the website (such asbase.htmlor include the required JavaScript code in a dedicated footer file.This JavaScript file will include the logic for lazy loading libraries, as well as the instructions to initialize it.

<script src="path/to/your/lazyload.min.js"></script>
<script>
  document.addEventListener("DOMContentLoaded", function() {
    var lazyloadImages = document.querySelectorAll("img[data-src]");
    var lazyloadThrottleTimeout;

    function lazyload () {
      if(lazyloadThrottleTimeout) {
        clearTimeout(lazyloadThrottleTimeout);
      }    
      lazyloadThrottleTimeout = setTimeout(function() {
          var scrollTop = window.pageYOffset;
          lazyloadImages.forEach(function(img) {
              if(img.offsetTop < (window.innerHeight + scrollTop)) {
                img.src = img.dataset.src;
                img.removeAttribute('data-src');
              }
          });
          if(lazyloadImages.length == 0) { 
            document.removeEventListener("scroll", lazyload);
            window.removeEventListener("resize", lazyload);
            window.removeEventListener("orientationChange", lazyload);
          }
      }, 20);
    }

    document.addEventListener("scroll", lazyload);
    window.addEventListener("resize", lazyload);
    window.addEventListener("orientationChange", lazyload);
  });
</script>

Please note that the above JavaScript code is a simplified example, and it is recommended to use a third-party lazy loading library with more comprehensive features and better compatibility in actual applications.

将上述代码(或您选择的懒加载库的初始化代码)放置在您的AnQiCMS模板的 English<head>标签底部或 English</body>Ensure that the label is executed after the DOM content has been loaded.After deployment, you can verify it through the Network tab of the browser developer tools: observe whether the image is in the "Pending" state before it scrolls into the visible area of the page, and it starts loading only after entering the viewport.

Through the services provided by AnQiCMS,lazy="data-src"The article content images on the website will achieve smooth on-demand loading with the help of the front-end lazy loading script.This will significantly improve the initial page loading speed, enhance the browsing experience of users, reduce server bandwidth consumption, and bring better SEO performance to your website.This is a highly cost-effective optimization strategy that is worth careful configuration by every AnQiCMS user.


Common Questions (FAQ)

Q1: 为什么AnQiCMS仅仅是把 Englishsrc变成了data-src,还需要前端JavaScript来实现懒加载?A1: This step of AnQiCMS is preparing for lazy loading technology. Browsers will load by defaultsrcThe image in the attribute, without caringdata-src. Place the image address indata-srcEnglish, can prevent the browser from downloading images when the page is initially loaded. The role of front-end JavaScript is to monitor these images withdata-srcWhen the picture of the property enters the user's visible area and assigns it a value at the appropriate time,data-srcDynamically assigns the value tosrcProperty, thus triggering the image loading. This is a typical mode of front-end and back-end collaboration to implement performance optimization.

Q2: I inserted an image into the article editor, and I need to manually modify the HTML code to add it.data-src?A2: Usually not required. If you are using in AnQiCMS template filesarchiveDetailwhen labeling outputting article content has been configuredlazy="data-src"参数,AnQiCMS系统会在渲染文章内容时自动将编辑器中图片的EnglishsrcThe attribute converts todata-srcThis means you can normally insert images in the editor, and the system will handle the subsequent attribute conversion.

Q3: Will lazy loading affect the crawling and indexing of images in search engines?A3: The modern search engine (especially Google) has already matured in handling lazy-loaded content. As long as you follow the standard methods (such as usingdata-src