【问题标题】:Load image in angular-cli app with rel="preload"使用 rel="preload" 在 angular-cli 应用程序中加载图像
【发布时间】:2026-01-22 03:50:01
【问题描述】:

我有一个 angular-cli 应用程序,我想为其预加载图像。我将以下标签放在我的 index.html <head>:

<link rel="preload" as="image" href="assets/img/cards/10_of_clubs.png">
...

那些链接不是 404。也就是说,指向的资源会在浏览器中加载:&lt;myhost&gt;/assets/img/cards/10_of_clubs.png

但是预加载不起作用,因为样式表中生成了 URL:

.r-10.s-3 {
  background-image: url(../../assets/img/cards/10_of_clubs.png);
}

导致不同的 URL,例如:/10_of_clubs.c7b975e5edc1b3444d45.png

我想做的是以某种方式引用我 index.html 中资产目录中的图像,并让 angular-cli 使用它们的“编译”URL 来引用它们。

顺便说一句,我也试过了:

img = new Image();
img.src = '../assets/img/cards/10_of_clubs';

在我的 Typescript 中,但这似乎再次引用了我在 index.html 尝试中得到的相同路径。

【问题讨论】:

  • 为此,您可以使用像 s13.postimg.org/ih41k9tqr/img1.jpg" onerror="this.src='../assets/img/cards/10_of_clubs;this.onerror=' 这样的 javascript 标签';" alt="用户图片">

标签: html angular angular-cli


【解决方案1】:

您可以使用这些代码来显示图像。

@Component({
   selector:'loading-image',
   template:'<img [src]="srcImg"/>'
})
srcImg:string = "../assets/img/cards/img.jpg"

【讨论】:

    【解决方案2】:

    添加--output-hashing=bundles,将生成没有哈希的图像。

    ng build --prod --output-hashing=bundles
    

    注意:图像文件名中的 HASH 有助于在每次构建后 managing browser cache

    【讨论】: