Document.write method questions

I am experimenting with the write and onload method. Here is my code:

<!DOCTYPE html>
<html>
    <head>
    </head>
    <body onload="document.write('body loaded!')">
        <h1>Hello World!</h1>
        <img onload="document.write('img loadeld!')" src="smiley.gif" alt="Smiley face" width="42" height="42" />
    </body>
</html>

If I run this in a browser, it displays “img loadeld” and just “freezes”, it seems to load the page endlessly. I expected the browser to output "img loadeld", and then when the body element is ready, "body is loaded" and just stops, as usual.

My questions:

  • Why such a hang? Why is the onload event on the img element blocking the browser from continuing and rendering "body loaded"?
  • Why, if I remove the onload handler from the img element, the response will be as expected - "body loaded" and the page is not locked.
+5
source share
5 answers

( , ), "" "". , . , :

IMG onload ( ).

document.write(), , .

, document.write() (docs) document.open() (docs), . write , . , (document.close()(docs), " ".

, ( , , , ):

  • , , document.write ( , )
  • IMG ,
  • document.write
  • ( , , )
  • document.write()
  • , .

DOM (appendChild(), innerHTML ..) document.write, , .

, , , , . , .

+3

, document.write() DOM ready DOM.

+2

document.write html, html. onload - , <img onload="document.write('img loadeld!')"/>= img.onload = function(event){document.write('img loadeld!');}.
, html-.

0

Which, since it document.write()clears the entire document and then writes the argument to the page, try document.writeln('Img loaded');adding to the body but stick to what you really want:

<img onload="document.body.innerHTML += '<h1>Loaded</h1>'"'

Or write a function that creates an element and use document.body.appendChild(elem), in which case you can replace document.bodywith any element of the block

0
source

Create a message container, such as a DIV, and set innerHTML, do not use .write ()

0
source

All Articles