This is a chunk of javascript code from a tutorial where they are trying to load an image onto a canvas and do some manipulations later on. I have omitted most of the irrelevant code to make it simpler to understand.
1) I fail to understand why the line containing the filename of the image is always put below the imageObj.onload function . Does it matter ? At what point does the image start getting loaded ?
2) What will happen if I forget to put the source of the image file.
<script>
window.onload = function(){
....
var imageObj = new Image();
imageObj.onload = function(){
....
....
});
....
....
};
imageObj.src = "yoda.jpg";
};
</script>
This is a somewhat historical issue. The order from
.onloadand.srcdoesn’t really matter (it’ll work technically on both orders), the issue is that some browsers (some = Internet Explorers) will take the image from the cache if available, as soon as thesrcattribute is set.That is why you should always declare an
onloadhandler before settingsrc.If you just forget to set the
srcattribute, just nothing will happen at all. If you don’t hold any more references or closures to that object, it will just get garbage collected as soon as possible.