我正在开发一个用于 iPad 的纹理选择器。所以基本上只是一堆图像元素。为了避免图像重新加载和滞后,我Image
在 JS 中缓存和重用对象。这样的
/**
* Asynchronous version of memoize for use with callback functions. Asserts
* that last argument is the callback.
*
* @param {Function} func
* @return {Function}
*/
util.memoize.async = function(func) {
var cache = {};
return function() {
var hash = JSON.stringify(arguments);
var args = Array.prototype.splice.call(arguments, 0);
var callback = args.pop();
if (hash in cache) {
return callback.apply(this, cache[hash]);
}
args.push(function() {
cache[hash] = Array.prototype.splice.call(arguments, 0);
callback.apply(this, cache[hash]);
});
return func.apply(this, args);
};
};
/**
* Creates new Image element and calls back with loaded image.
* @param {string} url
*/
io.GetImage = function(url, callback) {
var img = new Image();
img.onload = function() {
callback(img);
};
img.src = url;
};
picker.image_ = util.memoize.async(io.GetImage);
然后,每当我需要图像时,我都会调用picker.image_
并获取缓存的图像。它在桌面、Chrome、Firefox、Safari 上完美运行,但在 iPad 上,我得到的是空(未加载)图像。这是为什么?我真的很喜欢这种方法,它表现得非常好。
看起来好像 Mobile Safari 在从 DOM 中删除图像数据时会丢弃它。可以吗?
更新:为了澄清,正在加载的数据是动态的,因此它不是AppCache最合适的用例。
更新*:没有完全令人满意的答案,这是我的解决方案。请注意,复制方法非常慢。
/**
* Creates new Image element and calls back with loaded image.
* @param {string} url
*/
var GetImage = function(url, callback) {
var img = new Image();
img.onload = function() {
callback(img);
};
img.src = url;
};
/**
* @param {number} num maximum number of stored images
*/
var ImagePool = function(num) {
this.limit_ = num;
this.canvases_ = {};
this.order_ = [];
};
/**
* Retrieve image from cache.
*
* @param {string} url URL of request image
* @param {function(HTMLCanvasElement)} callback
*/
ImagePool.prototype.get = function(url, callback) {
if (this.canvases_[url] !== undefined) {
callback(this.copy_(url));
} else {
if (this.limit_ && this.order_.length == this.limit_) {
delete this.canvases_[url];
this.order_.pop();
}
GetImage(realUrl, function(img) {
var c = document.createElement('canvas');
c.width = img.width;
c.height = img.height;
var ctx = c.getContext('2d');
ctx.drawImage(img, 0, 0);
this.canvases_[url] = c;
this.order_.unshift(url);
callback(this.copy_(url));
}.bind(this));
}
};
/**
* @param {string} url
* @return {HTMLCanvasElement}
* @private
*/
ImagePool.prototype.copy_ = function(url) {
var c = document.createElement('canvas'),
cached = this.canvases_[url];
c.width = cached.width;
c.height = cached.height;
var ctx = c.getContext('2d');
ctx.drawImage(cached, 0, 0);
return c;
};