In the digital age, the speed of website access has become one of the key indicators for measuring user experience and search engine ranking.Images are often an important component of web content and can also be a major factor affecting page loading speed.When a page contains a large number of high-definition images, the browser needs to load all image resources before rendering the page, which undoubtedly increases the user's waiting time.This problem led to the emergence of the image lazy loading (Lazy Loading) technology.
The core idea of lazy loading images is to delay loading images that are not within the current viewport (i.e., the visible area on the user's current screen).Only when the image is about to enter or has already entered the user's viewport, should the request and loading of the real image resource begin.This strategy can significantly reduce the number of resource requests and data transmission during the first page load, thereby accelerating the rendering speed of the page, saving user bandwidth, and having a more obvious effect on improving the user experience of mobile devices. At the same time, it also helps to improve the SEO performance of the website.
AnQiCMS as a high-efficiency, customizable enterprise-level content management system took full consideration of website performance optimization from the beginning of its design.It provides a flexible template engine syntax, allowing users to finely control the display of front-end content, which greatly facilitates our implementation of image lazy loading.
AnQiCMS supports lazy loading of images in the content area
AnQiCMS's template engine syntax is similar to Django templates, controlling content output through various tags.For the content area of the article detail page, AnQiCMS provides a very convenient built-in lazy loading mechanism.When displaying article content, we can usearchiveDetaillabel'slazyParameter, allowing the system to automatically replace images in the content withsrcProperties with custom properties (for exampledata-src), and insert a placeholdersrc.
Specifically, when you usearchiveDetailtags to output document contentContentyou can write the template code like this:
{% archiveDetail articleContent with name="Content" lazy="data-src" %}
{{ articleContent|safe }}
{% endarchiveDetail %}
In this code block,lazy="data-src"The parameter will indicate the AnQiCMS template engine, during processingarticleContentWhen searching for HTML content in a variable, find all<img>tags. Once found, it will move the originalsrcattribute value to a property nameddata-srcand willsrcThe attribute is set to a default blank placeholder image address (usually a very small transparent GIF).
For example, if there was originally an image in your article content<img src="https://en.anqicms.com/uploads/images/example.jpg" alt="示例图片">Afterlazy="data-src"The processed HTML structure that will be output to the front-end page might be:
<img src="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==" data-src="https://en.anqicms.com/uploads/images/example.jpg" alt="示例图片">
At this time, the browser will only load that tiny placeholder GIF, without immediately loading the actualexample.jpg.
Extend lazy loading to other image elements
Although AnQiCMS provides built-in lazy loading for the article content area, the images on a website are not limited to the article content. For example, the thumbnails on the article list page, the cover images on the product detail page, the Banner images on the category page, etc., are usually loaded througharchiveList/archiveDetail/pageDetail/categoryDetailretrieve labels directlyLogo/ThumborImagesfields to display. For these images directly outputted through template tags, we need to make some manual adjustments.
Include the general steps to implement these lazy loading images:
Modify the image tags in the template:You need to find all the images output directly (such as
Logo/Thumbfields) of<img>tags, and manually change theirsrcThe attribute should be changed to a placeholder and the actual image address should be stored indata-srcthe attribute. For example, a code that originally displays an article thumbnail might be:<img src="{{ item.Thumb }}" alt="{{ item.Title }}">You need to change it to:
<img src="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==" data-src="{{ item.Thumb }}" alt="{{ item.Title }}">Here
data:image/gif;base64,...It is a very small transparent GIF image, used as a temporary placeholder when the browser is loading. You can also use other loading images or custom styles as placeholders.Introduce JavaScript lazy loading logic:The next step is to add JavaScript code to listen for these with
data-srcThe image of the property. When they enter the user's viewport, the script will assigndata-srcthe real image address tosrcThe attribute triggers the loading of the image. A simple and modern implementation is to useIntersection ObserverAn API that can efficiently detect when elements enter or leave the viewport without complex scroll event listeners. You can add the following JavaScript code to your template file (for example, usually inbase.htmlthe file</body>Before the tag, or in a separate JS file and through{% system with name="TemplateUrl" %}Tag introduction):<script> document.addEventListener('DOMContentLoaded', function() { const lazyImages = 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; // 如果有 srcset 属性也需要处理 if (lazyImage.dataset.srcset) { lazyImage.srcset = lazyImage.dataset.srcset; } lazyImage.removeAttribute('data-src'); lazyImage.removeAttribute('data-srcset'); lazyImageObserver.unobserve(lazyImage); } }); }); lazyImages.forEach(function(lazyImage) { lazyImageObserver.observe(lazyImage); }); } else { // Fallback for browsers that do not support Intersection Observer lazyImages.forEach(function(lazyImage) { lazyImage.src = lazyImage.dataset.src; if (lazyImage.dataset.srcset) { lazyImage.srcset = lazyImage.dataset.srcset; } lazyImage.removeAttribute('data-src'); lazyImage.removeAttribute('data-srcset'); }); } }); </script>This script will traverse all elements with the attribute after the page has loaded.
data-srcproperties<img>Tag. If the browser supportsIntersection ObserverIt will create an observer to monitor these images. When the images enter the viewport, the observer callback function willdata-srcthe value tosrcand stop observing the image. For those that do not supportIntersection ObserverThe old browser, all images will be loaded immediately, ensuring compatibility.Optional CSS optimization:In order to enhance the user experience, you can also add some CSS styles for lazy-loading images.For example, give the image a minimum height to prevent the page content from jumping before the image is loaded, or add a background color/loading animation.
img[data-src] { display: block; /* 避免图片下方出现空白 */ min-height: 100px; /* 预设一个最小高度,防止页面跳动 */ background-color: #f0f0f0; /* 占位背景色 */ /* background-image: url('/public/static/images/loading.gif'); */ /* 也可以添加加载动画 */ background-repeat: no-repeat; background-position: center; }