图片预加载与懒加载css
由名字能够知道,图片的预加载
->当用户须要查看图片能够直接从本地缓存中取到(提早加载下来的),图片的懒加载
->是当用户一次性访问的图片数量比较多的时候,会减小请求的次数或者延迟请求,是一种服务器前端的优化
总结来讲:图片的预加载
在必定程度上增强了服务器的压力,图片的懒加载
在必定程度上减轻了服务器的压力
预加载
就是在咱们须要使用到图片资源的地方以前就先把这些图片资源加载下来,这样在咱们使用的地方就会直接从本地缓存中去取html
实现方式1 : 能够直接在使用以前报因此资源加载下来这样就会缓解当在须要使用的地方全部资源加载太慢而出现的反作用前端
//css .image { width: 100vw; height: 100vh; background: url("https://sqimg.qq.com/qq_product_operations/im/pcqq/9.0/firstscreen_img/BG-1.jpg"), url("https://sqimg.qq.com/qq_product_operations/im/pcqq/9.0/firstscreen_img/BG-1_1.jpg"), url("https://sqimg.qq.com/qq_product_operations/im/pcqq/9.0/firstscreen_img/BG-2_1.jpg"), url("https://sqimg.qq.com/qq_product_operations/im/pcqq/9.0/firstscreen_img/BG-4_1.jpg"), url("https://sqimg.qq.com/qq_product_operations/im/pcqq/9.0/firstscreen_img/BG-5_1.jpg"), url("https://sqimg.qq.com/qq_product_operations/im/pcqq/9.0/firstscreen_img/BG-1_1.jpg"); background-size: cover; opacity: 1; animation: bgmove 10s infinite; overflow: hidden;
实现方式2 : 可使用image 对象,每建立一个image对象的时候就给浏览器缓存了一张图片,在须要使用的极速加载浏览器
//js <script> var arr = [ "https://sqimg.qq.com/qq_product_operations/im/pcqq/9.0/firstscreen_img/BG-1_1.jpg", "https://sqimg.qq.com/qq_product_operations/im/pcqq/9.0/firstscreen_img/BG-2_1.jpg", "https://sqimg.qq.com/qq_product_operations/im/pcqq/9.0/firstscreen_img/BG-4_1.jpg", "https://sqimg.qq.com/qq_product_operations/im/pcqq/9.0/firstscreen_img/BG-5_1.jpg", ]; var imgs = [] preLoadImg(arr); //图片预加载方法 function preLoadImg(pars) { for (let i = 0; i < arr.length; i++) { imgs[i] = new Image(); imgs[i].src = arr[i]; } } </script>
补充一个小问题:当咱们建立
var imageobj = new image()
image 对象,直接给对象src赋值,能够追加到页面图片能够显示,可是当咱们打印image对象的宽高时显示都是为0的,那时由于即便图片已经通过了预加载可是图片的加载速度仍是会慢于html的加载速度,因此解决办法就是使用onload方法,在图片已经彻底加载完成以后再打印,这样就能够取到图片的宽高了.
懒加载
自定义一个属性存放img的真实地址,在img 的src属性存放一个占位的图片地址(小图或者是图片加载的动图),当img出如今浏览器的可视区域时再将真实的图片地址赋值给img的src属性,减轻服务器端的压力缓存
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> img { margin-top: 1000px; } </style> </head> <body> <div class="container"> <img id="img1" src="https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=2167624966,4016886940&fm=26&gp=0.jpg" data-src="https://sqimg.qq.com/qq_product_operations/im/pcqq/9.0/firstscreen_img/BG-4_1.jpg" alt=""> </div> </body> </html> <script> var viewPortHeight = window.innerHeight; let $img1 = document.getElementById('img1'); function viewport(el) { return el.offsetTop - document.documentElement.scrollTop+200 <= viewPortHeight; } window.onscroll = function(){ //若是图片出如今页面的可视区域,就替换真实的图片 if(viewport($img1)){ console.log('图片出如今页面中'); //也能够在这里添加图片加载的动画 $img1.src = $img1.getAttribute("data-src"); }else{ console.log('图片没有出现'); } } </script>