【性能优化】图片性能优化方案
前言
通常可以通过 压缩图片、cdn、懒加载 等方式对图片进行性能优化
懒加载
通过 IntersectionObserver
监听
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title>
</head><body><img data-src="image.jpg" class="lazyload"><script>document.addEventListener('DOMContentLoaded', function () {const lazyImages = document.querySelectorAll('img.lazyload');if ("IntersectionObserver" in window) {const observer = new IntersectionObserver(function (entries, observer) {entries.forEach(entry => {if (entry.isIntersecting) {const image = entry.target;image.src = image.dataset.src;image.classList.remove('lazyload');observer.unobserve(image);}})})lazyImages.forEach(image => {observer.observe(image)})} else {lazyImages.forEach(image => {image.src = image.dataset.src;})}})</script>
</body></html>
监听滚动
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title>
</head><body><img data-src="default.png" class="lazyload"><script>document.addEventListener('DOMContentLoaded', function () {const lazyImages = document.querySelectorAll('img.lazyload');const lazyLoad = function () {lazyImages.forEach(function (img) {if (img.getBoundingClientRect().top <= window.innerHeight && img.getBoundingClientRect().bottom > 0 && getComputedStyle(img).display !== 'none' && img.getAttribute('data-src') !== null) {img.src = img.dataset.srcimg.classList.remove('lazyload')}})if (lazyImages.length === 0) {document.removeEventListener('scroll', lazyLoad)window.removeEventListener('resize', lazyLoad)window.removeEventListener('orientationchange', lazyLoad)}}document.addEventListener('scroll', lazyLoad)window.addEventListener('resize', lazyLoad)window.addEventListener('orientationchange', lazyLoad)})</script>
</body></html>