简短版本问题: 是否有适用于所有浏览器的 navigator.mozIsLocallyAvailable 等效函数或替代函数?
长版:)
嗨, 这是我的情况: 我想为 asp.net MVC 实现一个 HtmlHelper 扩展,它可以轻松处理图像后加载(使用 jQuery)。
因此,我使用“alt”属性中指定的源的空图像源渲染页面。 我在“window.onload”事件之后插入图像源,效果很好。
我做了这样的事情:
$(window).bind('load', function() {
var plImages = $(".postLoad");
plImages.each(function() {
$(this).attr("src", $(this).attr("alt"));
});
});
问题是:首次加载后,加载后的图像将被缓存。但如果页面加载时间为 10 秒,则缓存的加载后图像将在这 10 秒后显示。
因此,如果图像被缓存以立即显示它们,我认为在“document.ready”事件上指定图像源。
我找到了这个函数:navigator.mozIsLocallyAvailable来检查图像是否在缓存中。这是我用 jquery 所做的:
//specify cached image sources on dom ready
$(document).ready(function() {
var plImages = $(".postLoad");
plImages.each(function() {
var source = $(this).attr("alt")
var disponible = navigator.mozIsLocallyAvailable(source, true);
if (disponible)
$(this).attr("src", source);
});
});
//specify uncached image sources after page loading
$(window).bind('load', function() {
var plImages = $(".postLoad");
plImages.each(function() {
if ($(this).attr("src") == "")
$(this).attr("src", $(this).attr("alt"));
});
});
它适用于 Mozilla 的 DOM,但不适用于任何其他 DOM。我尝试了 navigator.isLocallyAvailable :相同的结果。
还有其他选择吗?
最佳答案
经过一番研究,我找到了解决方案:
这个想法是记录缓存的图像,在图像“加载”事件上绑定(bind)日志函数。 我首先想到将源存储在cookie中,但是如果没有cookie就清除缓存,这是不可靠的。此外,它还向 HTTP 请求添加了一个 cookie...
然后我遇到了魔法:window.localStorage ( details )
The localStorage attribute provides persistent storage areas for domains
正是我想要的:)。此属性已在 HTML5 中标准化,并且已适用于几乎所有最新浏览器(FF、Opera、Safari、IE8、Chrome)。
下面是代码(不处理 window.localStorage 不兼容的浏览器):
var storage = window.localStorage;
if (!storage.cachedElements) {
storage.cachedElements = "";
}
function logCache(source) {
if (storage.cachedElements.indexOf(source, 0) < 0) {
if (storage.cachedElements != "")
storage.cachedElements += ";";
storage.cachedElements += source;
}
}
function cached(source) {
return (storage.cachedElements.indexOf(source, 0) >= 0);
}
var plImages;
//On DOM Ready
$(document).ready(function() {
plImages = $(".postLoad");
//log cached images
plImages.bind('load', function() {
logCache($(this).attr("src"));
});
//display cached images
plImages.each(function() {
var source = $(this).attr("alt")
if (cached(source))
$(this).attr("src", source);
});
});
//After page loading
$(window).bind('load', function() {
//display uncached images
plImages.each(function() {
if ($(this).attr("src") == "")
$(this).attr("src", $(this).attr("alt"));
});
});
关于javascript - 加载后: check if an image is in the browser cache,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2446740/