For this to work, the onload handler function has to be assigned before the .src property is set because if the image is in the browser cache, onload may fire immediately before .onload is assigned, thus missing the event.