views:

61

answers:

1

Hi

I'm trying to preload a number of images generated on the server to a small website. The preloading is done using setWindowTimeout and uses an Image object, sets the onload callback and then applies the new request uri.

For some requests, the server may have to signal that the image is 'unchanged' and I'm doing it by sending done a small 1x1 pixel gif (seems like I need to send an actual image, returning empty content will cause the Image object to not fire onload). In my onload handler I would like to determine the size of the fetched image and then determine if I should update the visual image with the given image.

Below is a snippet of my current solution (the output is a div to help debug):

        refresh: function() {
        var newSrc = '/screenshot.ashx?tick=' + new Date().getTime();
        var imgObj = new Image();
        var self = this;

        // this is called when load is done
        imgObj.onload = function() {
            //if (imgObj.complete) 
            //  return;
            if (imgObj.width > 1 && imgObj.height > 1) {
                output.innerHTML += '<br/>Updating image:' + newSrc;
                img.src = newSrc; //fiddler shows no reload here, read from cache
            }
            else {
                output.innerHTML += '<br/>Empty image:' + newSrc;
            }
            self.setupNewRefresh();
        };

        output.innerHTML += '<br/>Loading image:' + newSrc;
        imgObj.src = newSrc;
    },

I seem to have two problems:

a) the imgObj.complete is false when the function is first called but it is only called once (hence my commenting it out) and

b) I can't seem to rely on the width or height property of the image when loaded. From my tests of fetch the 1x1 pixel, it sometimes reads out 50 which seems to be default when creating a new Image() and it sometimes reads out the correct size of 1.

My ultimate goal is to have a small chunk of javascript logic that queries the server for a new image periodically, does nothing if nothing new has happened (1 pixel image) or loads the new image. I might be going about it the wrong way here or have overlooked important properties or calls, so I'm happy to receive feedbacks.

EDIT: upon suggestion from mplungjan, I preloaded into a hidden div instead, which helped me with problem b). Still no solution to problem a) though; reports complete = false once and is not called again

A: 

I'll go ahead and answer my own question.

Preloading the image into a hidden element in the DOM instead of a code-level element was the trick for actually getting correct sizes (thanks mplungjan). The a) issue, namely the complete event, remains unsolved.

As a side note I ended up using the XMLHttpRequest instead as it allowed by to look at the size of the payload returned.

soren.enemaerke