In website operation, page loading speed and user experience are always the core concerns.Images are an important part of web content and often also a major factor affecting page loading speed.A high-definition large image can enhance the visual effect, but if too many images are not properly handled, it will slow down the website speed and make visitors hesitate.
Fortunately, Anqi CMS provides us with a very convenient lazy loading (Lazy Load) feature, which helps us effectively solve this problem.In simple terms, lazy loading of images means that images are not loaded all at once when the page is loaded, but rather they start loading when the user scrolls the page and the images are about to enter the visible area.This is like flipping through a thick book, you only flip through a few pages you are currently reading, not opening the whole book at once.
Why is image lazy loading so important?
The benefits of enabling lazy loading of images are multifaceted:
- Speed up the first page load time:The browser does not need to load all image resources at once, which reduces the initial number of requests and data transfer volume, allowing users to see the main content of the page faster.
- Save bandwidth resources:For users who may never scroll to the bottom of the page, neither their devices nor the server need to transfer image data that has not been viewed.
- Improve user experience:The page responds faster, users feel smoother while browsing the content, reducing the anxiety of waiting.
- Beneficial for SEO optimization:Search engines are increasingly emphasizing the page loading speed, faster website loading speed can help improve search rankings.
AnQi CMS is a system focused on providing an efficient, customizable content management solution, and pays attention to high concurrency, security, and scalability, naturally understands this, and provides built-in lazy loading support.
How does AnQi CMS support lazy loading of images?
In AnQi CMS, implementing lazy loading for images is actually very simple. You may have noticed carefully, when dealing with article content, the document detail tag of AnQi CMS (archiveDetail)Provided a very practicallazyparameter. This parameter is specifically used to handle content(Content)images in the field.
The document clearly states,Contentfield supports lazy loading of images, just need to uselazy="data-src"This label is enough. This means that when you output the article in the templateContentif you add thislazyparameter, the system will automatically convertContentall within<img>label'ssrcreplaces itsdata-srcProperty.
For example, an image that was originally<img src="https://en.anqicms.com/uploads/image.webp" alt="示例图片">The image, after passing throughlazy="data-src"After processing, it will become<img data-src="https://en.anqicms.com/uploads/image.webp" alt="示例图片">. At this time, the browser will not immediately load this image, but will wait for us to use JavaScript to determine whether the image has entered the visible area, and thendata-srcAssign the value againsrcto achieve lazy loading.
Manual operation: Enable image lazy loading
Below, we will step by step complete the enablement of lazy loading:
Step 1: Locate the template file
Generally, the display template of article content is located in a similar manner{模型table}/detail.htmlpath, for examplearticle/detail.htmlorproduct/detail.htmlIf you are not sure which file it is, you can check the corresponding classification or model's document template settings under the 'Content Management' -> 'Document Classification' or 'Content Model' in the background.
Find the template file used for the detail page of your article, for example, we takearticle/detail.htmlas an example.
Second step: ModifyarchiveDetailTag
Open this template file and find the content output section of the articlearchiveDetailLabel. It usually looks like this:
{%- archiveDetail articleContent with name="Content" %}
{{articleContent|safe}}
We need to add parameters to this label:lazy="data-src"Parameters, after modification, will become:
{%- archiveDetail articleContent with name="Content" lazy="data-src" %}
{{articleContent|safe}}
Here|safeThe filter is very important, it tells the template engine toarticleContentVariables are output as safe HTML content and not escaped. If this is missing, lazy loading may not workdata-srcthe attribute may not work properly.
After completing this step, all images in the article contentsrcThe properties have been converted todata-srcyou can directly use
Step 3: Introduce the lazy loading JavaScript library
merelysrcThe property todata-srcIt's not enough, we still need a JavaScript code to listen for page scrolling and move the value back todata-srcwhen the image enters the visible areasrcProperty.
You can choose a lightweight lazy loading library, such aslazysizes.jsOr write a simple script yourself. For demonstration, we provide one based on the native of modern browsersIntersection Observer APIA simple script, you can add it to the public header or footer template file of your website (for examplebase.html)的<script>within the</body>tag before, to ensure that the DOM elements have loaded:
<script>
document.addEventListener("DOMContentLoaded", function() {
// 获取所有带有 data-src 属性的图片
let 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;
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 older browsers (可选, 这里简化为直接加载)
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>
Fourth step: CSS styles may be needed (optional, but recommended)
To avoid the page content 'jitter' (Layout Shift) when the image loads, it is recommended to set a fixed width and height for the image or use CSS to reserve the image position. For example, you can add a minimum height to the image:
img[data-src] {
min-height: 100px; /* 根据实际图片比例调整 */
display: block; /* 避免一些行内元素的默认行为 */
}
Or, when publishing articles, make sure the images are accompanied bywidthandheightProperty.
Combined with other optimization methods, the effect is better
The Anqi CMS also provides other practical functions in image processing, which can make the website performance even better when used with lazy loading. You can find them in the "Content Settings" panel on the backend:
- Do you want to enable Webp image format:Enable this feature, and the uploaded JPG, PNG, and other images will be automatically converted to a smaller file size WebP format, further reducing the image size.
- Whether to automatically compress large images:When the size of the image you upload is too large, the system can automatically compress it to the specified width, effectively saving storage space and loading time.
- Thumbnail processing method and size:The website can automatically generate thumbnails of different sizes as needed by the frontend, ensuring that appropriate-sized images are loaded on list pages and other places.
By combining image lazy loading with these built-in image optimization features, your security CMS website will experience significant improvements in loading speed and user experience.
Frequently Asked Questions (FAQ)
Q1: I have followed the steps already inarchiveDetailtags.lazy="data-src", but the image seems to load immediately, why is that?
A1: The most common reason is that you may have forgotten to include the corresponding JavaScript lazy loading script in the website template, or the script may not be running correctly.lazy="data-src"Just to display the image'ssrcattribute todata-srcTo truly implement the "lazy" loading mechanism, JavaScript code is needed to listen to thesedata-srcWhen the image enters the user's visible area, then dynamically loaddata-srcAssign the value againsrcPlease check yourbase.htmlOr the related template file contains the correct JavaScript lazy loading script, and ensure that the script does not have syntax errors or is blocked from execution by other JS conflicts.
Q2: Enabling lazy loading of images will it have a negative impact on the SEO of the website??
A2: Just the opposite, modern search engines (especially Google) have a positive attitude towards lazy loading of images.Implementing lazy loading correctly usually has a positive impact on SEO.Search engines' crawlers can now typically execute JavaScript and recognizedata-srcProperties such as. Faster page loading speed, better user experience (Core Web Vitals metrics) are themselves important factors for SEO ranking.Just make sure that the lazy-loaded image content is still crawlable and indexable by search engines, and there are no JS errors that cause the image to fail to load, then there will be no problem.
Q3: Besides the images in the article content, can the other images on my website (such as banner images, thumbnails) also be lazy-loaded using this method?
A3:lazy="data-src"This parameter is specifically designed forarchiveDetailLabel outputContentThe image in the field is processed. For images in other locations on the website