In AnQiCMS, optimizing website loading speed is a key step to improve user experience and search engine rankings.When the article content contains a large number of images, these images will significantly increase the page loading time.Image lazy loading (Lazy Loading) is an efficient method to solve this problem, which allows images not to load before they enter the user's field of vision, thereby speeding up the initial rendering speed of the page.
AnQiCMS as a content management system that focuses on performance and SEO, provides flexible support for lazy loading of images in article content.You can easily enable this feature on your website by using simple template configuration combined with frontend JavaScript.
Understand the principle of image lazy loading
The core idea of lazy loading images is to delay loading the image resources within the viewport. Usually, the browser will download all<img>label'ssrcThe image specified by the attribute. Lazy loading technology stores the actual address of the image indata-src/data-originalcustom attributes, andsrcThe attribute points to a lightweight placeholder image (even if it is empty). When the user scrolls the page, the JavaScript code on the front end will capture this event and thendata-srcthe real image address tosrcThe image starts downloading and displaying.
How does AnQiCMS support lazy loading of article content images
AnQiCMS handles the detailed page content of articles and provides a built-in mechanism to assist in implementing image lazy loading. This is mainly reflected inarchiveDetailtags pairContentthe rendering of fields.
In the article detail page template, we usually usearchiveDetailtags to output the main content of the article. For example:
<div>文档内容:{% archiveDetail archiveContent with name="Content" %}{{archiveContent|safe}}</div>
To enable lazy loading, AnQiCMS allows you toarchiveDetaila tag toContentAdd a fieldlazyParameter. This parameter is used to inform AnQiCMS, in the rendering of article content in<img>when the tag is rendered,srcthe content of the attribute is replaced to the custom attribute you specified, and tosrcThe property is cleared or set to a placeholder.
Assuming you want to usedata-srcAs the storage attribute for the actual image address, you can modify your template code like this:
<div>文档内容:{% archiveDetail archiveContent with name="Content" lazy="data-src" %}{{archiveContent|safe}}</div>
Here, lazy="data-src"Indicates that AnQiCMS will move all<img>label'ssrctodata-srcproperties, at the same timesrcthe properties may be cleared.|safeThe filter is necessary here, it indicates that AnQiCMS will treat the output HTML content as safe content, without escaping, to ensure that image tags are rendered correctly.
After this step, the images in the article content will no longer be loaded directly throughsrcloading, but will wait for the intervention of front-end JavaScript.
Steps to implement lazy loading in front-end JavaScript
Simply modifying the template tags of AnQiCMS does not directly enable lazy loading of images. You also need to introduce a segment of JavaScript code to detect whether the images enter the visible area and trigger loading. This usually involves the following steps:
Choose a suitable lazy loading library or native support:Modern browsers already support it natively
loading="lazy"attribute, this is the simplest and most **performance** solution. You can add it in<img>tag directlyloading="lazy". When using AnQiCMS'slazy="data-src"if your JS lazy loading library can also loaddata-srctosrcwhilesrcwhile also containingloading="lazy"It can be used very well together. If you need to be compatible with old browsers, you can choose some lightweight frontend lazy loading libraries such asvanilla-lazyload/Lozad.jsorIntersection Observer APIA polyfill solution. These libraries usually listen to scroll events or useIntersection Observer APIto detect element visibility.to introduce JavaScript code into your template:You need to include the selected lazy loading JavaScript library file or custom JavaScript code into your website template. According to the AnQiCMS template conventions, static resource files are usually stored in
/public/static/Under the directory. You can add the public header template of the website (such aspartial/header.html) or the footer template (such aspartial/footer.html, usually before the</body>tag)。“For example, if you use the native
loading="lazy"and your JS logic is just todata-srctosrcyou can introduce a simple custom JS in this way:<!-- 引入自定义懒加载JS文件 --> <script src="{% system with name="TemplateUrl" %}/js/lazyload.js"></script>or, you can write the initialization code directly in HTML (not recommended for complex logic):
<script> document.addEventListener("DOMContentLoaded", function() { var 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; lazyImage.removeAttribute("data-src"); // 移除data-src属性 lazyImage.setAttribute("loading", "lazy"); // 添加原生懒加载属性 lazyImageObserver.unobserve(lazyImage); } }); }); lazyImages.forEach(function(lazyImage) { lazyImageObserver.observe(lazyImage); }); } else { // Fallback for older browsers without Intersection Observer // (e.g., attach to scroll, resize, orientationchange events) // This part can be more complex or use a dedicated library. let lazyLoadThrottleTimeout; function lazyload () { if (lazyLoadThrottleTimeout) { clearTimeout(lazyLoadThrottleTimeout); } lazyLoadThrottleTimeout = setTimeout(function() { let scrollTop = window.pageYOffset; lazyImages.forEach(function (img) { if (img.offsetTop < (window.innerHeight + scrollTop)) { img.src = img.dataset.src; img.removeAttribute("data-src"); img.setAttribute("loading", "lazy"); } }); lazyImages = lazyImages.filter(function (img) { return img.hasAttribute('data-src'); }); if (lazyImages.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 simple example to illustrate the lazy loading logic.In practice, you may need to configure and initialize in detail according to the official documentation of the lazy loading library you choose.
Summary of specific operation process
- Post or edit article:When publishing or editing articles on the AnQiCMS backend, simply insert the pictures normally without any special operations. The system will store these images in a standardized
<img>tag format. - Modify the article detail page template:Find your article detail page template (usually located in
/template/您的模板目录/{模型table}/detail.html), and it will output the article content:archiveDetailModify the tag to includelazy="data-src"in the form of parameters:<div class="article-content"> {% archiveDetail articleContent with name="Content" lazy="data-src" %}{{articleContent|safe}} </div> - Introduce and initialize lazy loading JavaScript:In the public template file of your website (for example)
base.html, usually before the<head>or</body>Before the tag) introduce the lazy loading JavaScript library you choose, and initialize it according to the documentation of the library.If you use the above native Intersection Observer example, you can directly paste the code.
Optimization and注意事项
- Avoid lazy loading of the first screen images:Images that appear in the user's view as the page loads (Above the Fold) are not recommended for lazy loading