简体   繁体   English

在iOS中使用JavaScript预加载图片

[英]Image preloading with javascript in iOS

Scenario 情境

I use two images namely 'car-light.png' and 'car-dark.png'. 我使用两个图像,即“ car-light.png”和“ car-dark.png”。 When user touches the image, which was car-light.png, it becomes car-dark.png. 当用户触摸图像(即car-light.png)时,它变为car-dark.png。

Here is the code I used. 这是我使用的代码。

<img src="car-light.png" id="car" ontouchstart="changeCar()">

In changeCar(), I wrote this code 在changeCar()中,我编写了这段代码

$("#car").attr('src','url(car-dark.png)');

Question

Is there a way to speed this up by preloading the image? 有没有办法通过预加载图像来加快速度? Or am I making too big a deal with fast loading time? 还是我在快速加载时间上做得太大了? If it is the case where pre-loading is necessary, is the following code correct? 如果需要预加载,以下代码正确吗?

var img1 = new Image();
img1.src = "car-dark.png";

function changeCar(imgName) 
{
    document[imgName] = img1;
}

and in HTML 和HTML

<img src="car-light.png" name="car" ontouchstart="changeCar('car')">

Putting this somewhere in your startup JS code will preload the image: 将其放在启动JS代码中的某个位置将预加载图像:

var img1 = new Image();
img1.src = "car-dark.png";

This will cause the image to be in the browser cache so it will load quickly if you use it later on in the action of the page. 这将导致图像位于浏览器缓存中,因此如果稍后在页面操作中使用它,它将快速加载。 You could use the img1 object directly, but often it's easier to just use the URL and let the browser fetch the image from it's memory cache like this: 您可以直接使用img1对象,但是通常更容易使用URL并让浏览器从其内存缓存中获取图像,如下所示:

<img src="car-light.png" id="car" ontouchstart="changeCar()">

function changeCar() {
    $("#car").attr('src','car-dark.png');
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM