This time I will bring you the image loading optimization method in the front-end project. What are the precautions for the method of image loading optimization in the front-end project? The following is a practical case, let's take a look.
Pictures are a very important part of the interface display effect. Picture loading is related to user experience and application performance. Common strategies for optimizing picture loading are: preloading and lazy loading.#preload-img{ background: url(http://example.com/image.png) no-repeat -9999px -9999px; }
window.onload = function () { let preload = document.createElement('div'); preload.id = 'preload'; document.body.appendChild(preload); }
window.onload = function () { let images = [ 'http://example.com/image1.png', 'http://example.com/image2.png', 'http://example.com/image3.png', ]; images.forEach((src) => { preload(src); }) }let preload = src => { let img = new Image(); img.src = src; }
Design Mode-Agent Mode, there was a method to implement lazy loading of images through virtual proxy
let imageEle = (function(){ let node = document.createElement('img'); document.body.appendChild(node); return { setSrc:function(src){ node.src = src; } } })();//代理对象let proxy = (function(){ let img = new Image(); img.onload = function(){ imageEle.setSrc(this.src); }; return { setSrc:function(src){ img.src = src; imageEle.setSrc('loading.gif'); } } })(); proxy.setSrc('example.png');
visible area Properties display corresponding images.
If it is a picture wall page, in order to avoid starting to load all the pictures, you need to set the default height for the picture.img{ min-height: 400px; }
let imgs = document.getElementsByTagName("img");let n = 0; //存储加载图片索引let lazyload= ()=> { let cHeight = document.documentElement.clientHeight; var scrollTop = document.documentElement.scrollTop || document.body.scrollTop; //滚动条距离顶部高度 for (let i = n,l = imgs.length; i < l; i++) { let img = imgs[i]; if (img.offsetTop < cHeight + scrollTop) { img.src = img.src == 'loading.gif'? img.getAttribute('data-src'):img.src; n = i + 1; } } }window.onscroll = lazyload;
Detailed explanation of JS inheritance
Using function throttling in JS
Use JS code to create barrage effect
The above is the detailed content of Image loading optimization methods in front-end projects. For more information, please follow other related articles on the PHP Chinese website!