性能优化案例之预加载:代理模式优化加载体验
前言:
当我们遇见大图片的时候,不想破坏其像素清晰度,又不想让前端体验感差,就可以用预加载的loading图片来展示, 等到真正的图片下载完,再替换回来。
代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>性能优化案例</h1> <!-- <img class="img1" src="" alt="" width="960"> --> <div class="img-con"> <img class="img2" src="" alt="" width="540"> </div> <button class="btn1"> 请求图片</button> <script> //预加载=》代理模式优化加载体验 let btn1 = document.querySelector('.btn1') btn1.onclick = function(){ let myImage = (function(){ let imgNode = document.querySelector('.img2') return { setSrc:function(src){ imgNode.src = src } } })() let proxyImage = (function(){ let img = new Image; img.onload = function(){ myImage.setSrc(this.src) } return { setSrc:function(src){ myImage.setSrc('./loading.gif'); img.src = src } } })() proxyImage.setSrc('./img1.jpg') } </script> </body> </html>