Tro*_*ott 15 javascript firefox canvas local-storage picturefill
(先发制人的罢工:如果你想把它标记为副本,请注意其他问题似乎在问"为什么我会收到这个错误?"我知道为什么我会收到这个错误;我想知道我是怎么回事可以检测我的JavaScript代码中的错误.它只出现在Firebug控制台中,当然,在加载图像时对用户来说是显而易见的.)
我正在使用picturefill来响应图像.我有一个针对图像上的load事件触发的回调.因此,每当有人调整浏览器窗口大小以便通过图片填充加载不同的图像时,回调就会运行.
在回调中,我正在通过画布将图像数据转换为dataURL,这样我就可以将图像数据缓存在localStorage中,这样即使用户离线也可以使用它.
请注意关于"离线"的部分.这就是为什么我不能依赖浏览器缓存.HTML5离线应用程序缓存无法满足我的需求,因为图像是响应式的.(有关响应图像与HTML脱机应用程序缓存不兼容的说明,请参阅"应用程序缓存是一个Douchebag".)
在Mac上的Firefox 14.0.1上,如果我将浏览器的大小调整到非常大的值,然后在大图像有机会完全加载之前将其重新调整为较小的值,则会激活加载图像.它最终报告Firebug控制台中的"图像损坏或截断",但不会引发异常或触发错误事件.代码中没有任何错误迹象.就在Firebug控制台中.同时,它在localStorage中存储截断的图像.
如何在JavaScript中可靠有效地检测此问题,以便我不缓存该图像?
以下是我遍历picturefill div以查找picturefill插入的img标签的方法:
var errorLogger = function () {
window.console.log('Error loading image.');
this.removeEventListener('load', cacheImage, false);
};
for( var i = 0, il = ps.length; i < il; i++ ){
if( ps[ i ].getAttribute( "data-picture" ) !== null ){
image = ps[ i ].getElementsByTagName( "img" )[0];
if (image) {
if ((imageSrc = image.getAttribute("src")) !== null) {
if (imageSrc.substr(0,5) !== "data:") {
image.addEventListener("load", cacheImage, false);
image.addEventListener('error', errorLogger, false);
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
这就是cacheImage()
回调的样子:
var cacheImage = function () {
var canvas,
ctx,
imageSrc;
imageSrc = this.getAttribute("src");
if ((pf_index.hasOwnProperty('pf_s_' + imageSrc)) ||
(imageSrc.substr(0,5) === "data:") ||
(imageSrc === null) || (imageSrc.length === 0)) {
return;
}
canvas = w.document.createElement("canvas");
canvas.width = this.width;
canvas.height = this.height;
ctx = canvas.getContext("2d");
ctx.drawImage(this, 0, 0);
try {
dataUri = canvas.toDataURL();
} catch (e) {
// TODO: Improve error handling here. For now, if canvas.toDataURL()
// throws an exception, don't cache the image and move on.
return;
}
// Do not cache if the resulting cache item will take more than 128Kb.
if (dataUri.length > 131072) {
return;
}
pf_index["pf_s_"+imageSrc] = 1;
try {
localStorage.setItem("pf_s_"+imageSrc, dataUri);
localStorage.setItem("pf_index", JSON.stringify(pf_index));
} catch (e) {
// Caching failed. Remove item from index object so next cached item
// doesn't wrongly indicate this item was successfully cached.
delete pf_index["pf_s_"+imageSrc];
}
};
Run Code Online (Sandbox Code Playgroud)
最后,这里是我在Firebug中看到的全文,其中URL已更改以保护有罪:
图像损坏或截断:http://www.example.com/pf/external/imgs/extralarge.png
看来,在更改标记的src
属性时img
,Firefox会触发一个load
事件.这与HTML5规范相反,HTML5规范说如果更改了src属性,那么任何其他正在进行的提取都应该结束(Firefox会这样做),并且不应该发送任何事件.在load
只有在获取成功完成事件应该被发送.所以我要说你得到一个load
事件的事实是一个Firefox的bug.
但是,图像应该知道它是否完全可用,您可以尝试使用该complete
属性:
if (this.complete === false) {
return;
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,Firefox已经this.complete
设置了true
,所以这也不是一个选择.
最佳选择可能是<img>
每次要更改src
属性时创建新元素.
归档时间: |
|
查看次数: |
21833 次 |
最近记录: |