In AnQiCMS, optimizing the website loading speed, especially handling pages with a large number of images, is an important factor in improving user experience and search engine rankings.Image lazy loading (Lazy Load) technology is a highly efficient solution that allows images to be loaded only when the user scrolls to their position on the page, rather than loading all images at once.For AnQiCMS users, implementing this feature has its unique advantages.
Why choose lazy loading for images?
There are too many images on the website, especially on article detail pages or product display pages, which often leads to long initial loading times of the page.Users may need to wait a few seconds to see the full content, which can easily lead to user attrition.Lazy loading technology can effectively solve this problem:
- Improve page loading speed:Reduce the number of HTTP requests and data transfers during initial loading, making the page appear faster to the user.
- Save bandwidth:Users only load the images they actually view, reducing unnecessary resource consumption.
- Improve user experience:Page content is visible faster, users do not have to wait, and the experience is smoother.
- Optimize SEO:Search engines are increasingly emphasizing page loading speed, lazy loading helps improve the ranking of websites in search results.
The core method to implement image lazy loading in AnQiCMS templates.
AnQiCMS's template engine (similar to Django syntax) provides a very direct and convenient solution for lazy loading of images in the content.
Scene one: Main text image of article or product details page
For images inserted into the content editor on the back end (i.e., stored in the documentContentThe image in the field), AnQiCMS provides a built-inlazyparameter that helps us automatically convert HTML image tags tosrcproperties todata-src.
You usually use tags to display document content in templates. To enable lazy loading, you just need to addarchiveDetailwhen fetchingContentthe fieldlazy="data-src"the parameter.
For example, in your document detail page template (such as{模型table}/detail.html), the code to display the article content might be like this:
{# 假设我们正在显示当前页面的文档内容 #}
<div>
{%- archiveDetail articleContent with name="Content" lazy="data-src" %}
{{articleContent|safe}}
</div>
In this code block:
{% archiveDetail articleContent with name="Content" ... %}Used to get the current documentContentContent, and assign it toarticleContentVariable.lazy="data-src"It is crucial. AnQiCMS template engine handlesContentfields, automatically recognizing the<img>the tag and use it.srcvalue of the properties and moves it todata-srcthe properties. At the same time, it usually willsrcSet the property to a placeholder (such as a transparent gif or a small logo) so that the page layout is not destroyed when the image is not loaded.{{articleContent|safe}}Means toarticleContentThe variable's content is safely output as HTML because it is obtained from the editor's HTML rich text.
This processing by the AnQiCMS template engine will automatically convert all image tags in your document content (such as<img src="https://en.anqicms.com/uploads/image.jpg">) into something similar<img src="/path/to/placeholder.gif" data-src="https://en.anqicms.com/uploads/image.jpg">The form. Next, you just need to include a JavaScript lazy loading library to handle thesedata-srcImage.
Scene two: List page thumbnails and other images (such as Logo, Thumb)
Except for the images in the document content, there are also many other images on the website, such as thumbnails of the article list page (item.Thumboritem.Logo), carousel images, Banner images, and so on. These images are usually notContentThe field is, therefore AnQiCMS built-in.lazyThe parameter will not take effect. For this type of image, we need to combine front-end JavaScript to implement lazy loading.
The implementation idea is:
- In the template, put the actual URL of the image into
data-srcthe attribute instead ofsrcProperty. srcAn attribute can point to a low-quality placeholder or a transparent GIF image.- Add a specific class to the image, such as
lazyload),convenient for JavaScript libraries to identify. - After the page is loaded, listen to these with JavaScript lazy loading libraries.
data-srcThe image of the property will be loaded when it enters the user's visible area,data-srcthe value will be copied back,srcthus triggering the actual loading of the image.
For example, using the thumbnail on the article list page (witharchiveListTag):
{# 假设这是文章列表页模板中的一个条目 #}
{% archiveList archives with type="page" limit="10" %}
{% for item in archives %}
<li>
<a href="{{item.Link}}">
<h5>{{item.Title}}</h5>
{# 这里是列表项的缩略图,手动设置data-src #}
{% if item.Thumb %}
<img class="lazyload" src="/static/images/placeholder.gif" data-src="{{item.Thumb}}" alt="{{item.Title}}">
{% else %}
<img class="lazyload" src="/static/images/placeholder.gif" data-src="/static/images/default-thumb.gif" alt="{{item.Title}}">
{% endif %}
<div>{{item.Description}}</div>
</a>
</li>
{% endfor %}
{% endarchiveList %}
In the above code:
- we give
<img>Tag addedclass="lazyload". src="/static/images/placeholder.gif"Is a preset placeholder image path.data-src="{{item.Thumb}}"ordata-src="/static/images/default-thumb.gif"Then stores the actual image URL.
Selection and integration of Lazy Loading JavaScript libraries
In order to make the aforementioneddata-srcThe image has taken effect, you need to introduce a lightweight JavaScript lazy loading library. There are many excellent libraries such asvanilla-lazyload/lozad.jsThey are usually very small and easy to configure.
The integration steps are roughly as follows:
- Import library files:In your public template files (such as
base.html)的<body>Before the tag ends, a JavaScript file for lazy loading libraries introduced through CDN or local files.{# 在 base.html 文件底部,</body> 标签前引入 #} <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/lazyload.min.js"></script> <script> // 初始化懒加载库 document.addEventListener("DOMContentLoaded", function() { var lazyLoadInstance = new LazyLoad({ elements_selector: ".lazyload" // 匹配所有带有lazyload类的元素 }); }); </script> - Initialize the library: According to the documentation of the library you choose, after the page is loaded (usually
DOMContentLoaded) initialize it, and specify the image selector to listen to (for example.lazyload)
Cautionary notes and **practice
- Native lazy loading
loading="lazy":Modern browsers (such as Chrome, Firefox) already support the nativeloading="lazy"properties. For projects that do not need to be compatible with old browsers, you can directly add in<img>the tagloading="lazy". This property can be combined with the JavaScript lazy loading library to be used as a progressive enhancement solution.
When the browser supports<img src="/static/images/placeholder.gif" data-src="{{item.Thumb}}" alt="{{item.Title}}" loading="lazy">loading="lazy"When it is available, it will load using the native method; when not supported, the JavaScript library will take over. - Fallback without JavaScript support:Consider users who have disabled JavaScript. You can
<noscript>place real images in tagssrcor set them initially.srcSet the property to a low-quality version of the image, ensuring that the image can be displayed even without JS (although it is not lazy-loaded). - Placeholder: Using an appropriate placeholder can prevent blank or jumping layout of page content before the image is loaded, improving user experience. It can be a small blurred image, a solid color background, or the website logo.
- Image size preset:To avoid layout shift (Cumulative Layout Shift, CLS), it is recommended to
<img>specify it in the tagwidthandheightProperties, or by using CSS to reserve space for the image container. This helps the browser calculate the layout before the image is loaded. - Comprehensive test:Test the lazy loading effect on different browsers and devices to ensure that images load normally and improve page performance.
By using the above method, you can flexibly implement lazy loading of images in the AnQiCMS template, whether using its built-inlazyParameter processing content image, or manually configure other imagesdata-srcCombined with front-end JavaScript libraries, they can effectively improve website performance and user experience.
Frequently Asked Questions (FAQ)
AnQiCMS'
lazyDoes the parameter automatically process all images?- AnQiCMS template in
lazyParameters such aslazy="data-src"主要用于处理从Content field(如文章或产品详情页的正文Content字段)中获取的HTML图片。对于模板中直接通过{{item.Logo}}/{{item.Thumb}}Images output in this way, you need to manually put them indata-srcproperty, and combine it with a front-end JavaScript library to implement lazy loading.
- AnQiCMS template in
How to ensure lazy loading works on all browsers including those that disable JavaScript users?
- For users who have disabled JavaScript, you can provide a fallback option. One common practice is to
<img>label'ssrcPlace a low-quality or small placeholder image in the attribute. A better solution is to utilize<noscript>Label: In regular<img>After the label, add a<noscript>Block containing a realsrcof<img>Label. In this way, if JavaScript is disabled, the browser will parse<noscript>the images. At the same time, consider using the browser's nativeloading="lazy"attribute for progressive enhancement.
- For users who have disabled JavaScript, you can provide a fallback option. One common practice is to
Does lazy loading affect the SEO of a website?
- Implementing lazy loading correctly usually has a positive impact on SEO.By reducing the initial page load time, it can improve the page performance score, which is exactly what search engines value.Modern search engines (such as Google) have crawlers that are mostly capable of executing JavaScript