Question

What is the difference between

<img id="el" src="HD.jpg" onload="loadImage();">
function loadImage() {...}

and

<img id="el" src="HD.jpg">
document.getElementById('el').onload=loadImage();

?

Example 1 triggers the function when the image is fully loaded, example2 triggers it even before the first bit of image is loaded. Isn't it supposed to be the same thing ?

The difference is hard to spot with a full speed internet access but obvious with a narrow one.

Notice that

document.getElementById('el').src.onload=loadImage();

doesn't work either.

Thanks

edit: sorry for the approximative post title, don't hesitate to suggest a proper one.

Was it helpful?

Solution

You are doing something quite different from what you think you're doing: you are assigning the value returned by loadImage to ..onload member of the img element.

What actually happens is that when your script loads, it assigns the result of calling loadImage() function (this is why you see it run before any images), which is most likely undefined to img.onload handler, thereby disabling it.

To do what you want, you need to assign a function to img.onload handler - for example - just wrap in another function:

document.getElementById('el').src.onload = function() { loadImage(); };

or you can directly assign your function as a handler. It nicely illustrates why it didn't work before, although I wouldn't recomend it:

document.getElementById('el').src.onload = loadImage;

(note missing ())

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top