当前位置:网站首页>Lazy loading and preloading of pictures
Lazy loading and preloading of pictures
2022-06-28 04:16:00 【weixin_ forty-seven million one hundred and sixty-four thousand】
Image lazy loading and preloading
One . background
At present, various e-commerce websites are emerging in endlessly , Everybody knows , There are a lot of pictures on e-commerce websites , In fact, it is not just e-commerce websites , There are others , Websites with high image density . Because of the large number of pictures , Long waiting time , And load too many resources , Cause some waste of resources , So this is the case , The user experience is very poor , So at this point , Lazy loading and preloading are good solutions
Two . Lazy loading
Lazy loading : Also known as deferred loading ( abbreviation lazyload), You can delay loading images in long web pages , It is a scheme to optimize the performance of web pages , Its core is load on demand
1. Why use lazy loading ?
(1) Enhance user experience If a long web page , Load all the pictures at once , The picture density is very high , Large number , Waiting time , The user certainly won't buy it , Close the web page and leave .
(2) Reduce invalid resource loading Load data as needed , Those that do not enter the viewport do not need to be loaded , You didn't even look at them , Why load it out . Therefore, the pressure and traffic of the server are obviously reduced , It can also reduce the rendering burden of the browser
(3) Prevent concurrent loading of too many resources , Blocking js Loading Affect the normal use of the website
2. The idea of lazy loading
(1) utilize Image Of src Only when there is a picture address can the picture be loaded
(2) The initial state of the picture is not set src attribute , Use a custom attribute to save the image path Such as data-src
(3) When the picture enters the viewable area of the window src assignment
(4) window.onscroll Determine whether the picture enters the window : Picture to body Of offsetTop<( Window height +scrollTop)
3. Lazy loading principle
Put the picture on the page src Property is set to null , Then the real path of the picture is stored in the custom attribute of the current picture label data-src On , When the page scrolls , Need to monitor scroll event , stay scroll Event callback , Judge whether our lazy loaded image is in the visible area , If the picture is in the visible area, the src Property is set to data-src Value , Then this is how to delay loading
Be careful : If the data is loaded asynchronously , We actually only need to make a request once , There is no need to request more than once
4. Implement lazy loading
<style>
.image-item {
display: block;
margin-bottom: 50px;
height: 200px;
/* Be sure to set the picture height */
}
</style>
//html
<img src="" class="image-item" lazyload="true" data-src="https://image.ztemall.com/e96bedfde1da7fe4430015588ded9e55.jpg"
<img src="" class="image-item" lazyload="true" data-src="https://image.ztemall.com/f4eb114554ae8d3d11a11bf0fa436b4a.jpg"
//html
<img src="" class="image-item" lazyload="true" data-src="https://image.ztemall.com/e96bedfde1da7fe4430015588ded9e55.jpg"
<img src="" class="image-item" lazyload="true" data-src="https://image.ztemall.com/f4eb114554ae8d3d11a11bf0fa436b4a.jpg"
//js
<script>
var viewHeight = document.documentElement.clientHeight;// Get the height of the viewing area
function lazyload() {
var eleImgs= document.querySelectorAll('img[data-src][lazyload]');
eleImgs.forEach(function (item, index) {
// If data-src Property has no value , Go straight back to
if (item.dataset.src === "")
return;
// Used to get the left side of an element in the page , On , The position of the right and bottom relative to the browser window respectively
var rect = item.getBoundingClientRect();
if (rect.bottom >= 0 && rect.top < viewHeight) {
(function () {
var img = new Image();
img.src = item.dataset.src;
img.onload = function () {
item.src = img.src;
}
item.removeAttribute("data-src");// Remove properties , No more traversal next time
item.removeAttribute("lazyload");
})()
}
})
}
lazyload();// When I didn't scroll the screen at first , To trigger a function first , Initialize the page image of the home page
document.addEventListener("scroll", lazyload);
</script>
3、 ... and . Preloading
Preloading : Load pictures in advance , When users need to view , Another performance optimization technique for web pages is to preload rendering resources directly from the local cache , We can use this technology to inform the browser in advance that some resources may be used in the future .
1. Why use preload
Before all the pages load , Load some of the main content , Provide users with a better experience , Reduce waiting time , If a long page , Too large , Preload not used , The page will be blank for a long time , Until all content is loaded
2. The idea of preloading
(1) Create a picture node to display 1
(2) Create a node to load pictures 2
(3) Monitor nodes 2 Of onload event
(4) Return an object , Contains a settings picture src Methods , node 1 Show local pictures , node 2 Load real resources
3. Common ways to achieve preloading
1. Use HTML label
<img src="https://image.ztemall.com/e96bedfde1da7fe4430015588ded9e55.jpg" style="display:none"/>
2. Use Image object
var image= new Image()
image.src="https://image.ztemall.com/e96bedfde1da7fe4430015588ded9e55.jpg"
3. Use ajax
No introduction here , There will be some cross domain problems
Four . The difference between lazy loading and preloading
1. Concept
(1) Lazy loading ( Delay loading ): Delayed image loading , Load only after the picture enters the viewport
(2) Preloading : Load pictures in advance , When users need to view , Read directly from the local cache
2. difference
Both are effective ways to improve page performance , The difference is that one is to load ahead of time , One is to delay loading or even not loading , Lazy loading can relieve the pressure on the front end of the server , Preloading will increase the pressure on the front end of the server
3. significance
(1) The main purpose of lazy loading is to optimize the front end of the server , Reduce the number of requests or delay requests .
(2) Preloading can be said to sacrifice server front-end performance , For a better user experience , In this way, the user's operation can be reflected as quickly as possible
边栏推荐
- After launching the MES system, these changes have taken place in the enterprise
- first. Net core MVC project
- Reading notes of top performance version 2 (II) -- Performance observation tool
- Component splitting practice
- Digital promising, easy to reach, Huawei accelerates the layout of the commercial market with "five pole" star products
- Uncertainty principle
- 第一个.net core MVC项目
- Tiktok actual battle ~ take off the blogger
- Multithreading and high concurrency II: detailed introduction to volatile and CAS
- [MySQL] multi table connection query
猜你喜欢

阿里P8倾情推荐,Fiddler抓包工具实战篇(一)

One article tells you what kubernetes is

How to write a software test report? Here comes the third party performance report template

抖音實戰~關注博主

How to apply for ASTM E108 flame retardant test for photovoltaic panels?

The company leader said that if the personal code exceeds 10 bugs, he will be dismissed. What is the experience?

Analysis of future teacher research ability under steam education framework

视频爆炸时代,谁在支撑视频生态网高速运行?

《性能之巅第2版》阅读笔记(二)--CPU监测

MSc 307 (88) (2010 FTPC code) Part 2 smoke and toxicity test
随机推荐
Component splitting practice
等保三级密码复杂度是多少?多久更换一次?
From zero to one, I will teach you to build a "search by text and map" search service (I)
僅用遞歸函數和棧操作逆序一個棧
视频爆炸时代,谁在支撑视频生态网高速运行?
leetcode:714. 买卖股票的最佳时机含手续费【dp双状态】
视频直播系统源码,倒计时显示,商品秒杀倒计时
Analyzing the comprehensive application ability of educational robot
Lingge leangoo agile Kanban tool adds the functions of exporting card documents and pasting shared brain map nodes
leetcode - 329. 矩阵中的最长递增路径
La norme européenne en 597 - 1 pour les meubles est - elle la même que les deux normes en 597 - 2 pour les ignifuges?
TFTLCD display experiment of mini plate based on punctual atom stm32
02 MongoDB数据类型、重要概念以及shell常用指令
Go语言学习教程(十四)
美创数据安全管理平台获信通院“数据安全产品能力验证计划”评测证书
第一个.net core MVC项目
利用 telegraf influxdb grafana 搭建服务器监控平台
领歌leangoo敏捷看板工具新增导出卡片文档和粘贴共享脑图节点功能
等保2.0密码要求是什么?法律依据有哪些?
Web APIs DOM event foundation dark horse programmer