You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular离线模式下重试页面Assets资源(图片/JSON)加载失败求助

Angular离线重试页面资源加载失败解决方案

方案1:资源内联,彻底避免网络请求

  • SVG内联:直接把done.svg的完整代码复制到重试页面的组件模板中,替换原来的<img src="/assets/done.svg">。示例:
    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
      <!-- 粘贴done.svg的原始代码到这里 -->
    </svg>
    
  • JSON动画内联:把retry.json的内容作为常量定义在组件的.ts文件里,直接在动画逻辑中引用这个常量,无需通过HTTP请求加载。示例:
    import { Component } from '@angular/core';
    
    @Component({
      selector: 'app-offline-retry',
      templateUrl: './offline-retry.component.html',
      styleUrls: ['./offline-retry.component.css']
    })
    export class OfflineRetryComponent {
      // 直接复制retry.json的内容到这里
      retryAnimation = {
        "frames": [...],
        "duration": 1000
      };
    }
    

方案2:用Service Worker预缓存资源

Angular的Service Worker可在应用首次加载时将指定资源缓存到本地,离线时直接从缓存读取:

  1. 确保项目已安装@angular/service-worker依赖:
    ng add @angular/pwa
    
  2. 修改ngsw-config.json,将需要缓存的资源加入assetGroups:
    {
      "$schema": "./node_modules/@angular/service-worker/config/schema.json",
      "index": "/index.html",
      "assetGroups": [
        {
          "name": "app-resources",
          "installMode": "prefetch",
          "resources": {
            "files": [
              "/assets/done.svg",
              "/assets/retry.json",
              "/favicon.ico",
              "/index.html"
            ]
          }
        }
      ]
    }
    
  3. 在angular.json的生产环境配置中开启Service Worker:
    "configurations": {
      "production": {
        "serviceWorker": true,
        "ngswConfigPath": "ngsw-config.json"
      }
    }
    
  4. 构建生产版本并部署,首次加载后资源会被缓存,离线时即可正常访问。

方案3:Base64编码资源

  • SVG转Base64:把done.svg转成Base64字符串,直接作为img的src值,示例:
    <img src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIiBzdHJva2U9ImN1cnJlbnRDb2xvciIgc3Ryb2tlLXdpZHRoPSIyIiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS1saW5lam9pbj0icm91bmQiPgo8cGF0aCBkPSJNMTIgMmM1LjUxNCAwIDEwIDQuNDg2IDEwIDEwcy00LjQ4NiAxMC0xMCAxMC0xMC00LjQ4Ni0xMC0xMCA0LjQ4Ni0xMCAxMC0xMFoiLz4KPC9zdmc+">
    
  • JSON转Base64:把retry.json转成Base64,在组件中解码使用:
    const retryJsonBase64 = "eyJmcmFtZXMiOlsxXSwiZHVyYXRpb24iOjEwMDB9";
    this.retryAnimation = JSON.parse(atob(retryJsonBase64));
    

内容的提问来源于stack exchange,提问作者sinan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 08:55:20