views:

560

answers:

3

Short version question : Is there navigator.mozIsLocallyAvailable equivalent function that works on all browsers, or an alternative?

Long version :)

Hi, Here is my situation : I want to implement an HtmlHelper extension for asp.net MVC that handle image post-loading easily (using jQuery).

So i render the page with empty image sources with the source specified in the "alt" attribute. I insert image sources after the "window.onload" event, and it works great.

I did something like this :

$(window).bind('load', function() {
    var plImages = $(".postLoad");
    plImages.each(function() {
        $(this).attr("src", $(this).attr("alt"));
    });
});

The problem is : After the first loading, post-loaded images are cached. But if the page takes 10 seconds to load, the cached post-loaded images will be displayed after this 10 seconds.

So i think to specify image sources on the "document.ready" event if the image is cached to display them immediatly.

I found this function : navigator.mozIsLocallyAvailable to check if an image is in the cache. Here is what I've done with 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"));
    });
});

It works on Mozilla's DOM but it doesn't works on any other one. I tried navigator.isLocallyAvailable : same result.

Is there any alternative?

+2  A: 

An ajax request for the image would return almost immediately if it is cached. Then use setTimeout to determine if its not ready and cancel the request so you can requeue it for later.

Update:

var lqueue = [];
$(function() {
  var t,ac=0;
  (t = $("img")).each(
    function(i,e)
    {
      var rq = $.ajax(
      {
        cache: true,
        type: "GET",
        async:true,
        url:e.alt,
        success: function() { var rq3=rq; if (rq3.readyState==4) { e.src=e.alt; } },
        error: function() { e.src=e.alt; }
      });

      setTimeout(function()
      {
        var k=i,e2=e,r2=rq;
        if (r2.readyState != 4)
        {
          r2.abort();
          lqueue.push(e2);
        }
        if (t.length==(++ac)) loadRequeue();
      }, 0);
    }
  );
});

function loadRequeue()
{
  for(var j = 0; j < lqueue.length; j++) lqueue[j].src=lqueue[j].alt;
}
McD
Thanks for your intersting answer. I've test it but there is a problem :(The sucess callback is immediatly triggered, far before the complete loading of the image.I tried to replace the "success" event by "complete", same thing. I think that the success/complete events are not waiting the loading of the components of the response to trigger.
Mathieu
Anyway the problem is that this solution double the HTTP request number. I would like to avoid that.
Mathieu
A: 

Hello, after some reseach, I found a solution :

The idea is to log the cached images, binding a log function on the images 'load' event. I first thought to store sources in a cookie, but it's not reliable if the cache is cleared without the cookie. Moreover, it adds one more cookie to HTTP requests...

Then i met the magic : window.localStorage (details)

The localStorage attribute provides persistent storage areas for domains

Exactly what i wanted :). This attribute is standardized in HTML5, and it's already works on nearly all recent browsers (FF, Opera, Safari, IE8, Chrome).

Here is the code (without handling window.localStorage non-compatible browsers):

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"));
    });
});
Mathieu
+1  A: 

Hi Mathieu,

I have a remark about your empty image sources. You wrote:

So i render the page with empty image sources with the source specified in the "alt" attribute. I insert image sources after the "window.onload" event, and it works great.

I've ran into problems with this in the past, because in some browsers empty src attributes cause extra requests. Here's what they do (copied from Yahoo! performance rules, there's also a blog post on that issue with more detail):

  • Internet Explorer makes a request to the directory in which the page is located.
  • Safari and Chrome make a request to the actual page itself.
  • Firefox 3 and earlier versions behave the same as Safari and Chrome, but version 3.5 addressed this issue[bug 444931] and no longer sends a request.
  • Opera does not do anything when an empty image src is encountered.

We also use a lot of jQuery on our site, and it has not always been possible to avoid empty image tags. I've chosen to use a 1x1 px transparent gif like so: src="t.gif" for images that I only insert after pageload. It is very small and gets cached by the browser. This has worked very well for us.

Cheers, Oliver

Oliver
Hi Oliver you're right about it. Another solution I used is a span set with the same width and height the image will be. Moreover, HTML5 have custom attributes so using it:<span data-lz-width="44" data-lz-height="44" data-lz-src="thing.jpg" data-lz-alt="The thing" class="lz"><noscript><img src="thing.jpg" alt=...></noscript></span>Then, the script replace the whole span by the image using the custom attributes information.Regards, Mathieu
Mathieu