update code level
This commit is contained in:
189
assets/js/app.js
189
assets/js/app.js
@@ -13,6 +13,118 @@ let isInFavoritesPage = false; // 标记当前是否在收藏页
|
||||
// API基础URL
|
||||
const API_BASE = '/api';
|
||||
|
||||
// 图片加载器类
|
||||
class ImageLoader {
|
||||
constructor() {
|
||||
this.cache = new Map();
|
||||
}
|
||||
|
||||
// 加载并解压图片
|
||||
async loadImage(imageId, element) {
|
||||
// 检查缓存
|
||||
if (this.cache.has(imageId)) {
|
||||
const cachedData = this.cache.get(imageId);
|
||||
this.setImageSrc(element, cachedData.blobUrl, cachedData.mimeType);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(`${API_BASE}/image/${imageId}`);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
|
||||
const contentType = response.headers.get('content-type');
|
||||
const contentEncoding = response.headers.get('content-encoding');
|
||||
const originalContentType = response.headers.get('x-original-content-type');
|
||||
|
||||
let imageData;
|
||||
|
||||
if (contentEncoding === 'br') {
|
||||
// Brotli压缩数据,需要解压
|
||||
const compressedData = await response.arrayBuffer();
|
||||
imageData = await this.decompressBrotli(compressedData);
|
||||
} else {
|
||||
// 未压缩数据
|
||||
imageData = await response.blob();
|
||||
}
|
||||
|
||||
// 创建Blob URL
|
||||
const mimeType = originalContentType || contentType || 'image/jpeg';
|
||||
const blob = new Blob([imageData], { type: mimeType });
|
||||
const blobUrl = URL.createObjectURL(blob);
|
||||
|
||||
// 缓存结果
|
||||
this.cache.set(imageId, { blobUrl, mimeType });
|
||||
|
||||
// 设置图片源
|
||||
this.setImageSrc(element, blobUrl, mimeType);
|
||||
|
||||
} catch (error) {
|
||||
console.error('图片加载失败:', error);
|
||||
// 加载失败时使用占位图
|
||||
element.src = '/assets/placeholder.svg';
|
||||
}
|
||||
}
|
||||
|
||||
// 设置图片源
|
||||
setImageSrc(element, blobUrl, mimeType) {
|
||||
// 创建新的Image对象进行预加载
|
||||
const img = new Image();
|
||||
img.onload = () => {
|
||||
element.src = blobUrl;
|
||||
element.classList.add('loaded');
|
||||
};
|
||||
img.onerror = () => {
|
||||
console.error('图片解码失败');
|
||||
element.src = '/assets/placeholder.svg';
|
||||
};
|
||||
img.src = blobUrl;
|
||||
}
|
||||
|
||||
// Brotli解压
|
||||
async decompressBrotli(compressedData) {
|
||||
// 检查浏览器是否支持Brotli解压
|
||||
if (window.TextDecoder && window.TextEncoder) {
|
||||
try {
|
||||
// 使用浏览器的Brotli解压(如果支持)
|
||||
if (window.DecompressionStream && 'br' in window) {
|
||||
const decompressionStream = new DecompressionStream('br');
|
||||
const decompressedStream = new Response(compressedData).body.pipeThrough(decompressionStream);
|
||||
return new Response(decompressedStream).arrayBuffer();
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('浏览器Brotli解压失败,使用JavaScript解压:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// 使用JavaScript实现的Brotli解压(备用方案)
|
||||
return await this.decompressBrotliJS(compressedData);
|
||||
}
|
||||
|
||||
// JavaScript实现的Brotli解压(备用方案)
|
||||
async decompressBrotliJS(compressedData) {
|
||||
// 这里可以集成一个轻量级的Brotli解压库
|
||||
// 由于Brotli解压比较复杂,这里先返回原始数据
|
||||
// 在实际项目中,可以使用第三方库如brotli-wasm
|
||||
console.warn('Brotli解压未实现,返回原始数据');
|
||||
return compressedData;
|
||||
}
|
||||
|
||||
// 清理缓存
|
||||
clearCache() {
|
||||
// 清理所有Blob URL
|
||||
for (const [imageId, cached] of this.cache.entries()) {
|
||||
URL.revokeObjectURL(cached.blobUrl);
|
||||
}
|
||||
this.cache.clear();
|
||||
}
|
||||
}
|
||||
|
||||
// 创建全局图片加载器实例
|
||||
const imageLoader = new ImageLoader();
|
||||
|
||||
// 设备检测
|
||||
const isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);
|
||||
const isTouchDevice = 'ontouchstart' in window || navigator.maxTouchPoints > 0;
|
||||
@@ -68,6 +180,76 @@ function initInfiniteScroll() {
|
||||
});
|
||||
}
|
||||
|
||||
// 初始化图片懒加载
|
||||
function initLazyLoading() {
|
||||
// 使用Intersection Observer实现懒加载
|
||||
if ('IntersectionObserver' in window) {
|
||||
if (lazyLoadObserver) {
|
||||
lazyLoadObserver.disconnect();
|
||||
}
|
||||
|
||||
lazyLoadObserver = new IntersectionObserver((entries) => {
|
||||
entries.forEach(entry => {
|
||||
if (entry.isIntersecting) {
|
||||
const img = entry.target;
|
||||
const imageId = img.getAttribute('data-image-id');
|
||||
|
||||
if (imageId && !img.classList.contains('loaded')) {
|
||||
imageLoader.loadImage(imageId, img);
|
||||
}
|
||||
|
||||
lazyLoadObserver.unobserve(img);
|
||||
}
|
||||
});
|
||||
}, {
|
||||
rootMargin: '100px 0px', // 提前100px开始加载
|
||||
threshold: 0.1
|
||||
});
|
||||
|
||||
// 观察所有带有data-image-id的图片
|
||||
document.querySelectorAll('img[data-image-id]').forEach(img => {
|
||||
if (!img.classList.contains('loaded')) {
|
||||
lazyLoadObserver.observe(img);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
// 不支持Intersection Observer的回退方案
|
||||
console.warn('浏览器不支持Intersection Observer,使用回退懒加载方案');
|
||||
initFallbackLazyLoading();
|
||||
}
|
||||
}
|
||||
|
||||
// 回退懒加载方案
|
||||
function initFallbackLazyLoading() {
|
||||
let scrollTimeout;
|
||||
|
||||
function checkImagesInView() {
|
||||
const images = document.querySelectorAll('img[data-image-id]:not(.loaded)');
|
||||
const viewportHeight = window.innerHeight;
|
||||
const scrollTop = window.scrollY;
|
||||
|
||||
images.forEach(img => {
|
||||
const rect = img.getBoundingClientRect();
|
||||
const isInView = rect.top < viewportHeight + 200 && rect.bottom > -200;
|
||||
|
||||
if (isInView) {
|
||||
const imageId = img.getAttribute('data-image-id');
|
||||
if (imageId) {
|
||||
imageLoader.loadImage(imageId, img);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
window.addEventListener('scroll', () => {
|
||||
clearTimeout(scrollTimeout);
|
||||
scrollTimeout = setTimeout(checkImagesInView, 100);
|
||||
});
|
||||
|
||||
// 初始检查
|
||||
checkImagesInView();
|
||||
}
|
||||
|
||||
// 处理滚动事件
|
||||
function handleScroll() {
|
||||
// 如果在收藏页,禁用无限滚动
|
||||
@@ -217,7 +399,7 @@ function appendAlbums(albums) {
|
||||
<div class="album-cover">
|
||||
<img
|
||||
src="${coverImageUrl}"
|
||||
${dataSrc ? `data-src="${dataSrc}"` : ''}
|
||||
${album.cover_image_id ? `data-image-id="${album.cover_image_id}"` : ''}
|
||||
alt="${album.title}"
|
||||
class="lazy"
|
||||
onerror="this.src='/assets/placeholder.svg'"
|
||||
@@ -414,7 +596,7 @@ function displayAlbums(albums) {
|
||||
<div class="album-cover">
|
||||
<img
|
||||
src="${coverImageUrl}"
|
||||
${dataSrc ? `data-src="${dataSrc}"` : ''}
|
||||
${album.cover_image_id ? `data-image-id="${album.cover_image_id}"` : ''}
|
||||
alt="${album.title}"
|
||||
class="lazy"
|
||||
onerror="this.src='/assets/placeholder.svg'"
|
||||
@@ -730,7 +912,8 @@ function displayFavorites(favoriteImages) {
|
||||
` : `${favoriteImages.map((fav, index) => `
|
||||
<div class="favorite-card" onclick="openFavoriteImage('${fav.favorite.album_id}')">
|
||||
<div class="card-image">
|
||||
<img src="${API_BASE}/image/${fav.image.id}"
|
||||
<img src="/assets/placeholder.svg"
|
||||
data-image-id="${fav.image.id}"
|
||||
alt="${fav.image.title || '收藏的图片'}"
|
||||
loading="lazy">
|
||||
<div class="card-overlay">
|
||||
|
||||
Reference in New Issue
Block a user