Should setting an image src to data URL be available immediately?
As no one has yet found any specifications about how this is supposed to behave, we will have to be satisfied with how it does behave. Following are the results of my tests.
| is image data usable right | does onload callback set after src | after setting src? | is changed still get invoked?------------+-----------------------------+-------------------------------------Safari 5 | yes | yes ------------+-----------------------------+-------------------------------------Chrome 8 | **no** (1st page load), but | yes FireFox 3.6 | yes thereafter (cached) | ------------+-----------------------------+-------------------------------------IE8 | yes (32kB data limit) | yes ------------+-----------------------------+-------------------------------------IE9b | yes | **no** ------------+-----------------------------+-------------------------------------
In summary:
- You cannot assume that the image data will be available right after setting a data-uri; you must wait for the
onload
event. - Due to IE9, you cannot set the
onload
handler after setting thesrc
and expect it to be invoked. - The recommendations in "Playing it Safe" (from the question above) are the only way to ensure correct behavior.
If anyone can find specs discussing this, I will happily accept their answer instead.
After giving control back to the browser's rendering engine, the test reports true
in FF 4b9 and Chromium 8.0.552.237. I modified these parts:
img.onload = function(){ // put this above img.src = … document.getElementById('onload').innerHTML = 'yes';};img.src = img_src;…window.setTimeout(function () { // put this inside setTimeout document.getElementById('wh').innerHTML = (img.height==img.width) && (img.height==128);}, 0);
Update: Yes, I understand this 'answer' is more like a comment, but just wanted to point it out. And after testing I get reproducible results:
- without
setTimeout
, in both browsers I getfalse
the first time I open the page andtrue
only after hitting F5. After explicitly clearing the cache both sayfalse
again after reloading. - with
setTimeout
the width/height test always evualuates totrue
.
In both cases the image doesn't show up the first time, only after reloading the page.