EDIT: Actually I may have been wrong apparently different browsers behave differently in this respect and although the image is available information such as it's width and height aren't necessarily. I assume this is because the browser functions that calculate this information are non-blocking and assume you are listening to onload
.
So yes listen to the onload
event to ensure that a dynamic image has been loaded by the users browser before attempting to use it.
Based on information from: Should setting an image src to data URL be available immediately?
Ignore the following advice (it remains to provide context to my answer):
By storing it as a variable you are in a way preloading it. All that happens when you preload an image is it's data is retrieved and stored. You have already stored it's data in a variable - what is there to preload?
Because variable assignment is synchronous the image will be available to your code that follows.
The whole point of preloading is the fact that an image is usually at a different location on the server and that loading of separate files is often asynchronous thus you ensure that your script waits for the image to be downloaded. By creating your image inline you are effectively storing it in the JavaScript file and it will be downloaded at the same time.