实践记录以及工具使用 | 豆包MarsCode AI 刷题

55 阅读2分钟

1. 图片优化

1.1 动态裁剪与响应式加载

使用 HTML 的 srcsetsizes 属性动态加载不同分辨率的图片。

ini
 代码解读
复制代码
html
复制代码
<img 
  src="default.jpg" 
  srcset="small.jpg 480w, medium.jpg 1024w, large.jpg 1920w" 
  sizes="(max-width: 480px) 480px, 
         (max-width: 1024px) 1024px, 
         1920px" 
  alt="Responsive Image">

1.2 使用现代格式 (WebP/AVIF)

javascript
 代码解读
复制代码
javascript
复制代码
function supportsWebP() {
    const canvas = document.createElement('canvas');
    return canvas.getContext && canvas.toDataURL('image/webp').indexOf('data:image/webp') === 0;
}

if (supportsWebP()) {
    document.querySelector('img').src = 'image.webp';
} else {
    document.querySelector('img').src = 'image.jpg';
}

1.3 图片压缩工具

使用 sharp 压缩图片:

javascript
 代码解读
复制代码
javascript
复制代码
const sharp = require('sharp');

sharp('input.jpg')
  .resize(800) // 调整宽度为 800 像素
  .toFormat('webp')
  .toFile('output.webp', (err, info) => {
    if (err) console.error(err);
    else console.log('Image optimized:', info);
  });

2. 前端资源优化

2.1 代码分割与按需加载

使用 Webpack 的动态导入实现按需加载模块:

java
 代码解读
复制代码
// 主代码
import(/* webpackChunkName: "dashboard" */ './dashboard').then(module => {
    const dashboard = module.default;
    dashboard.init();
});

2.2 启用 Brotli 压缩

在服务器配置 Brotli 压缩以减少静态资源体积。例如,Nginx 配置:

bash
 代码解读
复制代码
gzip on;
gzip_proxied any;
gzip_types text/plain text/css application/json application/javascript;
gzip_vary on;

brotli on;
brotli_comp_level 6;
brotli_types text/plain text/css application/json application/javascript;

2.3 使用 Service Worker 缓存资源

通过 Service Worker 实现缓存:

csharp
 代码解读
复制代码
self.addEventListener('install', event => {
    event.waitUntil(
        caches.open('static-v1').then(cache => {
            return cache.addAll([
                '/',
                '/styles.css',
                '/script.js',
                '/image.jpg'
            ]);
        })
    );
});

self.addEventListener('fetch', event => {
    event.respondWith(
        caches.match(event.request).then(response => {
            return response || fetch(event.request);
        })
    );
});

3. 数据请求优化

3.1 GraphQL 示例

通过 GraphQL 合并请求,只发送一次 API 调用获取所有需要的数据:

bash
 代码解读
复制代码
query GetProducts {
    products {
        id
        name
        price
    }
    categories {
        id
        name
    }
}

在前端调用:

css
 代码解读
复制代码
fetch('/graphql', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ query: `
        query {
            products { id name price }
            categories { id name }
        }
    ` })
})
.then(response => response.json())
.then(data => console.log(data));

3.2 延迟加载与分页

实现滚动分页加载:

javascript
 代码解读
复制代码
window.addEventListener('scroll', () => {
    if (window.innerHeight + window.scrollY >= document.body.offsetHeight) {
        loadMoreData();
    }
});

function loadMoreData() {
    fetch('/api/products?page=2')
        .then(res => res.json())
        .then(data => {
            data.forEach(product => {
                const item = document.createElement('div');
                item.textContent = product.name;
                document.body.appendChild(item);
            });
        });
}

作者:Xoet
链接:juejin.cn/post/743963…
来源:稀土掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。