I am a bit confused here. I thought that the function specified in window.onload did not execute before the page was loaded. Nervertheless, I get an error in the below code (heres the jsfiddle version):
<script>
function updateImage(url){
document.getElementById("foo").src = url;
}
window.onload = updateImage("http://dummyimage.com/100x100/000/fff.png&text=qux");
</script>
<img id="foo" alt="" src="http://dummyimage.com/100x100/000/fff.png&text=bar" />
It gives me:
Error: document.getElementById("foo") is null
When moving the image above the script all works well.
window.onloadexpects to be a function – which it will call when the page is loaded. But what you’ve assigned to it is not a function. You assignedwhich immediately executes the
updateImagefunction, and since you don’t have areturnstatement in the body ofupdateImage, the return value isundefined. Therefore, at the end,window.onloadhas the valueundefined.A solution would be to change that bit of code to:
This will cause it to call the function when the window has been loaded and do what you’d expect.