In modern web environments, the loading speed of websites is one of the key factors affecting user experience and search engine rankings.When the web page content 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 image lazy loading (Lazy Loading) technology came into being.It does not load all the images on the page at once, but loads only those that enter or are about to enter the visible area based on the user's scrolling behavior.This will make the page load faster initially, significantly reduce resource consumption, and greatly improve the user experience.
The Anqi CMS has fully considered the needs of content optimization from the beginning of its design. It not only pursues high performance in system architecture but also provides a convenient lazy loading implementation for image content.For images in document content (such as articles, product details, etc.), the Anqi CMS can flexibly configure images to support lazy loading through its powerful template engine.
Implement the core secret of image lazy loading
In the AnQi CMS, the image lazy loading of document content is mainly realized by modifying the tags used in the template to display article details. The key isarchiveDetailTags, especially when you need to display articlesContentfields. The document content field itself supports a parameter namedlazywhich is the core of implementing lazy loading of images.
In simple terms, when you use a templatearchiveDetailtags to get and render document content, you can add in theContentfield calllazy="data-src"attribute.lazyThe property will indicate that the security CMS template engine will, when rendering HTML,<img>Tagssrcattribute in the content withdata-src(or any property name you define), and the actual image path will be stored in thisdata-src属性中。例如,原本<img src="path/to/image.jpg">will be rendered as<img data-src="path/to/image.jpg">,并且通常不会有src属性(或者src属性指向一个占位图)。
逐步实施:让文档图片动起来
To implement lazy loading of images in the document content on your CMS website, you usually need the following steps:
Prepare a front-end lazy loading libraryImages lazy loading usually requires the use of a JavaScript library to complete. There are many lightweight and efficient lazy loading libraries available for selection, such as
vanilla-lazyload/lozad.jsorlazysizes。They work in a similar way, all of them listen to the page scroll event, when the image enters the visible area,data-srcAssign the real image address in tosrcattribute to trigger the image loading.You need to select a frontend lazy loading library that you like, and download its file (usually
.jsand.css) to the static resource directory of your website, such as/public/static/jsor/public/static/css.Modify the template file to enable
lazyPropertyFind the template file used in the detail page of your document. According to the template conventions of Anqi CMS, this is usuallytemplate/{你的模板目录}/{模型table}/detail.htmlOr the custom document template file you created (for example,archive/detail.html).In this template file, you will find the content to display the articles.
archiveDetailTag call. The original code may look like this:{%- archiveDetail articleContent with name="Content" %} {{articleContent|safe}}To enable lazy loading, you need to in
archiveDetailofContentField additionlazyParameters. Assuming the frontend lazy loading library you choose expects images to be useddata-srcattribute to indicate lazy loading images, then you modify it like this:{%- archiveDetail articleContent with name="Content" lazy="data-src" %} {{articleContent|safe}}Here are the
lazy="data-src"tells the AITemplate engine in the rendering of AITCMSarticleContentAll variables<img>Tags will besrcmodified to the properties you specifydata-src.|safeThe filter is indispensable, it ensures that HTML content can be correctly parsed and displayed, rather than being escaped into plain text.Introduce and initialize the front-end lazy loading libraryAfter completing the template modification, you still need to introduce and initialize the frontend lazy loading library you choose in the public header or footer of the website. This is usually in
template/{你的模板目录}/bash.htmlorbase.htmlthe file.In
</body>Before the label, introduce your JavaScript file, and initialize it according to the library's documentation.vanilla-lazyloadFor example, you may need to add code similar 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 sure
elements_selectorthe value matches thearchiveDetailthe label settings.lazyattribute name.
Benefits of lazy loading: not just speed
The benefits of implementing lazy loading for images are multifaceted:
- Improve page loading speedWhen a user opens the page, only the visible images on the first screen need to be loaded, which greatly shortens the waiting time.
- Save bandwidth resourcesFor the unscrolled page area, images are not loaded, reducing the traffic consumption of the server and the user.
- Optimize search engine ranking:Faster page loading speed is an important ranking factor for search engines like Google, which helps to improve the SEO performance of a website.
- Improve user experience:A website with quick response makes users more pleasant, reduces the bounce rate, and improves the overall interactivity of the website.
Tip: Some 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: English
- Enable WebP image format:Automatically convert uploaded JPG, PNG images to a smaller WebP format, further reducing the size of the image files.
- Automatic compression of large imagesEnglish: Automatically compress images that are too large in size, which can ensure display quality and save storage space.
- Thumbnail processing method:Flexible settings for generating thumbnails and sizes, ensuring that small-sized images are loaded in scenarios such as list pages and recommended positions.
These functions work together to enable your security CMS website to achieve an excellent balance in content presentation and performance.
Common Questions (FAQ)
1. I have set up according to the steps.lazy="data-src"Also introduced lazy loading JS library, but why is the image not lazy loading?This may be due to several reasons:
- The JS library is not initialized correctlyPlease carefully check your front-end JS code, ensure that the lazy loading library is correctly introduced, and the initialization function is called. Pay special attention.
elements_selectorwhether the configuration matches.data-srcproperty matching. - HTML rendering issues.Check the browser developer tools to see if the image tag is actually rendered as
<img data-src="xxx">This format. If it is still<img src="xxx">That may be because the template file was not updated correctly or the template cache of CMS was not cleared, please try to refresh the cache. - CSS style conflict: Some CSS properties (such as
display: none;)May interfere with the lazy loading library's judgment of image visibility.
2. About CMS of safetylazyattribute can be set todata-originalor other name?OK, about CMS of safetylazyThe parameter design is very flexible, the document clearly states that it can be usedlazy="{定义的src名}". This means you can set it according to the requirements of the front-end lazy loading library you chooselazy="data-original"/lazy="data-src-alt"Ensure that the name you set in the template matches any name. But please make sure that the attribute name you set in the template matches the attribute name initialized by the front-end JS library.lazywith the attribute name initialized when the front-end JS library is initialized.elements_selectorconfigured in the template.
3. Image lazy loading has a negative impact on the website's SEO?Under normal circumstances, correctly implemented image lazy loading ispositive for SEO.The search engine (especially Google) is already able to crawl and index images that use lazy loading well.Faster page loading speed is inherently an important SEO ranking factor.
- Ensure
data-srcor similar properties contain clickable image URLs, rather than empty. - Avoid overly aggressive lazy loading strategies, that is, images start loading long before the user scrolls, which may cause the images to appear only when the user really needs them, affecting user experience.
- Add meaningful
altattributes, which helps search engines understand the content of the image. Anqi CMS supports setting Alt attributes when uploading images.