Obsidian Zettelkasten 终极指南:用开源模板库构建你的第二大脑
2026/5/6 11:45:28
在Web应用中,对静态资源(如CSS、JavaScript、图片、字体等)加载失败的场景进行降级处理,可以显著提升用户体验和应用的健壮性。
为关键静态资源提供备用方案,当主资源加载失败时自动切换。
<link>/<script>的onerror事件:<!-- CSS回退 --><linkrel="stylesheet"href="main.css"onerror="this.href='fallback.css'"><!-- JS回退 --><scriptsrc="main.js"onerror="this.src='fallback.js'"></script><imgsrc="image.jpg"onerror="this.src='placeholder.jpg';this.alt='加载失败'">@font-face{font-family:'CustomFont';src:url('custom-font.woff2')format('woff2'),url('fallback-font.woff2')format('woff2');/* 备用字体 */}通过Service Worker拦截资源请求,在离线或加载失败时返回缓存或备用资源。
// service-worker.jsself.addEventListener('fetch',(event)=>{event.respondWith(caches.match(event.request).then((cachedResponse)=>{returncachedResponse||fetch(event.request).catch(()=>{// 返回备用资源或默认页面returncaches.match('/offline.html');});}));});通过JavaScript动态加载资源并设置超时时间,超时后使用备用资源。
functionloadScriptWithTimeout(url,timeout,fallbackUrl){returnnewPromise((resolve,reject)=>{constscript=document.createElement('script');script.src=url;script.onload=resolve;script.onerror=()=>{// 加载失败时尝试备用资源constfallbackScript=document.createElement('script');fallbackScript.src=fallbackUrl;fallbackScript.onload=resolve;fallbackScript.onerror=reject;document.head.appendChild(fallbackScript);};document.head.appendChild(script);// 设置超时setTimeout(()=>{if(!script.onload){script.remove();constfallbackScript=document.createElement('script');fallbackScript.src=fallbackUrl;fallbackScript.onload=resolve;document.head.appendChild(fallbackScript);}},timeout);});}// 使用示例loadScriptWithTimeout('main.js',3000,'fallback.js').then(()=>console.log('脚本加载成功')).catch(()=>console.error('所有脚本加载失败'));<scriptsrc="https://cdn1.example.com/lib.js"></script><scriptsrc="https://cdn2.example.com/lib.js"defer></script><!-- 备用 --><imgsrc="image.jpg"onerror="this.src='data:image/svg+xml,...';this.alt='占位图'">window.addEventListener('error',(event)=>{if(event.targetinstanceofHTMLScriptElement||event.targetinstanceofHTMLLinkElement){console.error('资源加载失败:',event.target.src||event.target.href);// 上报错误到监控系统}});<link rel="preload">提前加载,减少失败概率。<linkrel="preload"href="critical.js"as="script">