Javascript Image.onLoad Broken

A Javascript Problem, and a Solution

Heres my code:

        var target = '';
        var loadstr = '';
        var webcamimg = '';

        function runwebcam(ttarget) {
                target = ttarget;
                webcamimg = new Image();
                loadstr = "http://lsrfm.com/images/webcam/lsr_studio.jpg?" + Math.random();
                webcamimg.src = loadstr;
                webcamimg.onLoad = gowebcam();
        }

        function gowebcam() {
                //stuff
        }

Thru the use of FireBug I’ve discovered that the function onLoad declared by onLoad is executing regardless of whether the image has finished being downloaded, which was my understanding as per TechRepublics Article.

So after a bit of hunting around I found this from Talideon.com.

So my adjusted code now reads:

        function runwebcam(ttarget) {
                target = ttarget;
                webcamimg = new Image();
                loadstr = "http://lsrfm.com/images/webcam/lsr_studio.jpg?" + Math.random();
                webcamimg.src = loadstr;
                webcamimg.onLoad = gowebcam();
        }
        function gowebcam() {
                if (!webcamimg.complete) {
                        setTimeout("gowebcam()", 500);
                        return;
                }
                //stuff
        }

Update:

Video of before/showing the fucked-upness

And Not fucked

4 thoughts on “Javascript Image.onLoad Broken”

  1. Barry,
    It might be that the image has loaded but it has not yet been rendered, so you’ll see weird stuff like the image having 0 width and height. I don’t see any code where you put your image into the document (I’m sure it’s in gowebcam() though).

    1. I use javascript to dynamically create a element and append it to the contents of a Div, in the gowebcam function,
      So it was still showing as loading in Firebug, and doing the scroll appear in the browser, (like a non js load an inline img tag)

      I hand’t considered the rendering of the image, as the scroll load made me think more that it was still downloading, like when a webpage first loads…

  2. Put the onload before assigning the image URL. Otherwise the onload will not fire reliably.
    The image may already have been loaded before you assign onload.

    function runwebcam(ttarget) {
    target = ttarget;
    webcamimg = new Image();
    loadstr = “http://lsrfm.com/images/webcam/lsr_studio.jpg?” + Math.random();
    webcamimg.onLoad = gowebcam();
    webcamimg.src = loadstr;
    }

Leave a Reply