HTML压缩:
<!DOCTYPE html><html><head> <meta charset="UTF-8"> <title>HTML压缩示例</title></head><body> <h1>这是标题</h1> <p>这是一段文本</p></body></html>复制代码
CSS压缩:
body { background-color: #f8f8f8; font-family: Arial, sans-serif; font-size: 16px;}h1 { color: #333; font-size: 28px;}p { color: #666; font-size: 18px;}复制代码
JavaScript压缩:

(function() { var message = "Hello World!"; console.log(message);}());复制代码
2.延迟加载
延迟加载可以利用JavaScript来实现。
<img data-src="image.jpg" alt="图片"><script> // 等待页面完备加载后再实行脚本 window.onload = function() { // 获取所有图片标记 var images = document.querySelectorAll('img[data-src]'); // 遍历图片标记 Array.prototype.forEach.call(images, function(image) { // 修正 src image.setAttribute('src', image.getAttribute('data-src')); }); };</script>复制代码
3.
<img data-src="image.jpg" alt="图片"><script src="https://code.jquery.com/jquery-3.5.1.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.lazyload/1.9.1/jquery.lazyload.min.js"></script><script> $(function() { $("img").lazyload({ effect: "fadeIn", threshold: 200 }); });</script>复制代码
4.利用缓存
可以利用HTTP缓存来缓存资源,以减少加载韶光。
做事器端设置缓存:
<?php$expires = 60 60 24 30; // 30天header("Cache-Control: max-age={$expires}, public");header("Expires: " . gmdate("D, d M Y H:i:s", time() + $expires) . " GMT");?>复制代码
客户端设置缓存:
<img src="image.jpg" alt="图片" width="300" height="200" /><script> if ('caches' in window && 'fetch' in window) { // 判断是否支持缓存和fetch API caches.match('image.jpg').then(function(response) { if (response) { // 从缓存加载图片 var img = document.querySelector('img'); img.src = response.url; } else { // 要求图片并把它缓存 fetch('image.jpg').then(function(response) { return caches.open('my-cache-name').then(function(cache) { cache.put('image.jpg', response.clone()); var img = document.querySelector('img'); img.src = response.url; }); }); } }); }</script>复制代码
5.压缩图像
可以利用工具和在线网站来压缩图像,如TinyPNG、Kraken等。
<img src="image.jpg" alt="图片" width="300" height="200" />
作者:兴科Sinco链接:https://juejin.cn/post/7228180483338371128著作权归作者所有。转载自稀土掘金