使用 JavaScript 预加载图像的选项

Back to All Posts

返回所有帖子

There are a number of ways to preload an image on demand with JavaScript — each with their own strengths & drawbacks. Let's explore them.

有多种方法可以用 JavaScript 按需预加载图像—每种都有自己的优势和缺点。让我们来探索它们。

[

[

Alex MacArthur /

Alex MacArthur /

](https://macarthur.me/about)Mar 30, 2026

](https://macarthur.me/about)Mar 30, 2026

I just learned that the task of preloading images with JavaScript is surprisingly quirky. There are actually several ways to do it, and the best one to choose can very much depend on the circumstances. Let's explore them through the lens of what I was trying to accomplish before running into all of this.

我刚刚了解到,用 JavaScript 预加载图像的任务出奇地古怪。实际上有几种方法可以做到这一点,选择最佳方法很大程度上取决于具体情况。让我们通过我之前试图实现的目标的视角来探索它们。

The Scene

场景

The latest version of JamComments supports dragging and pasting images into the comment box. It feels very much like dropping an image into a GitHub PR:

最新版本的 JamComments 支持将图像拖拽并粘贴到评论框中。感觉很像将图像拖入 GitHub PR:

pasting image into comment box

pasting image into comment box

将图像粘贴到评论框中

When building this out, everything looked great, up until comment submission, when the "pending" comment would be tacked to the top of the list. At that point, that image would be rendered for the first time. But because it hadn't actually been fetched yet, it would annoyingly load in after the comment had been mounted:

在构建这个时,一切看起来都很棒,直到评论提交时,"pending" 评论会被添加到列表顶部。那时,该图像将首次渲染。但因为它实际上还没有被获取,它会在评论挂载后烦人地加载:

image slowly loads in after comment is submitted

image slowly loads in after comment is submitted

评论提交后图片缓慢加载

Icky, but solvable. I just needed to fetch that newly uploaded image behind the scenes as soon as it was uploaded. By the time the user submitted the comment, it would already be cached and snap right in.

讨厌,但可解决。我只需要在图片上传后立即在后台获取那个新上传的图片。到用户提交评论时,它已经缓存好了,会瞬间加载进来。

A Lotta Ways to Preload

预加载的诸多方法

At the time, I was aware of two primary ways to preload images in JavaScript (as you'll see later, I've since bumped into a few more). If you do a quick Google, chances are you'll get this one first:

当时,我知道在 JavaScript 中预加载图像的两种主要方法(正如你稍后会看到的,我后来又遇到了更多几种)。如果你快速 Google,很可能会首先得到这个:

Option #1...

开通本站会员,查看完整译文。

首页 - Wiki
Copyright © 2011-2026 iteam. Current version is 2.155.1. UTC+08:00, 2026-04-01 23:41
浙ICP备14020137号-1 $访客地图$