You need to wait until the image is loaded (or completed if it is saved in the cache). This will result in an asynchronous callback operation:
// pure JS: var img = new Image(); img.src = myDataString; if (img.complete) { // was cached alert('img-width: '+img.width); } else { // wait for decoding img.onload = function() { alert('img-width: '+img.width); } }
Note. I once had the same problem with a project using jQuery. jQuery does not provide access to the image immediately enough immediately after its creation. This seems impossible to do, but in pure JS. But you can try timeout and wait for img-width to matter (and catch any errors when loading / decoding).
[Edit, see also comments] Why it works (why there is no racial state):
JS is single-threaded, which means that only one piece of code is currently running. Any events will be queued until the current area is displayed and will only fire. Thanks to late binding, any listeners will be evaluated only then (after completing the current area). Thus, the handler will be present and listened as soon as the onload-Event is triggered, regardless of whether the listener was configured before or after setting the src attribute. In contrast, the full flag is set as soon as the src attribute is set.
source share