Everything is working correctly (though not as you expected), and nothing is "hanging" or "blocking." It's all happening so fast, however, that it does not appear as such. Hopefully an explanation of the workings of writing to the document and the order of events will assist you:
Your IMG onload event fires after the document has been closed (document ready has been reached).
document.write()
, however, can only output to an open document.
If a document has been closed, document.write()
(docs) implicitly calls document.open()
(docs) which wipes the entire document. Your call to write
then outputs what you told it to. The document remains open until it is explicitly closed (document.close()
(docs)), so the "loading spinner" continues to show.
The basic flow of operations, then, which is taking place (so quickly that you don't notice it all happening and things look broken) is:
- page request made
- page response received
- document is opened, content is parsed and put into place, including the first
document.write
(does not have to call open because document is currently open)
- document closes
- Retrieval for the IMG tag completes and the event fires
- event handler calls
document.write
- document is implicitly re-opened (new doc created, all content lost; loading spinner displayed)
- your argument to
document.write()
is outputted into the new document
- everything is complete, document is still open
DOM manipulation techniques (appendChild()
, writting to innerHTML
, etc) should be used Instead of document.write
in order to modify existing content without overwriting everything.
The good news in this is that since this is happening, you do know that your image is loading successfully. You just gotta work out the right way to react to it as I eluded to earlier.
Hello World!