我使用的图像需要在您单击时更改,为此我使用了 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/