javascript - 使用前预加载图像

标签 javascript html css

我使用的图像需要在您单击时更改,为此我使用了 JavaScript onclick。我第一次在加载图像时执行此操作时有一个简短的“轻弹”,但这只发生在第一次。有没有一种方法可以预加载第二张图片,以便第一次可以像其他所有图片一样平滑地更改它?

最佳答案

预加载图像是改善用户体验的好方法。您有 3 种使用 CSS、JavaScript 或 Ajax 预加载图像的方法:

方法一:使用CSS和JavaScript预加载

#preload-01 { background: url(http://domain.tld/image-01.png) no-repeat -9999px -9999px; }
#preload-02 { background: url(http://domain.tld/image-02.png) no-repeat -9999px -9999px; }
#preload-03 { background: url(http://domain.tld/image-03.png) no-repeat -9999px -9999px; }

By strategically applying preload IDs to existing (X)HTML elements, we can use CSS’ background property to preload select images off-screen in the background. Then, as long as the paths to these images remains the same when they are referred to elsewhere in the web page, the browser will use the preloaded/cached images when rendering the page. Simple, effective, and no JavaScript required.

方法 2:仅 Javascript

var images = new Array()
function preload() {
    for (i = 0; i < preload.arguments.length; i++) {
        images[i] = new Image()
        images[i].src = preload.arguments[i]
    }
}
preload(
    "http://domain.tld/gallery/image-001.jpg",
    "http://domain.tld/gallery/image-002.jpg",
    "http://domain.tld/gallery/image-003.jpg"
)

来源: Perishable Press

关于javascript - 使用前预加载图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25449263/

相关文章:

javascript - 由于 (true/false) 变量,CSS 文本颜色发生变化

javascript - 替换javascript中的换行符

javascript - 通过 JS 自动提交表单(超时、时间间隔)

javascript - 如何只画垂直线和水平线(Canvas)

javascript - 将 ul 列表保存到 json 对象中

html - 如何在 Web 应用程序中加入换行符? (HTML,CSS)

jquery - 现场触摸滚动会暴露空白

javascript - 无法渲染 TIFF 图像并将其添加为结构对象

javascript - google.Timer.callOnce 不满足形参 : Google Closure

css - Bootstrap v4 - 制作垂直对齐的用户名片