Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm experimenting with write method & onload event. 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 browser it outputs "img loadeld" and just "hangs", seems to be loading the page infinitely. I expected the browser outputs "img loadeld" and then as the body element is ready "body loaded" and just stops as normally.

My questions:

  1. Why is there such a hang? Why the onload event on img element blocks the browser from continuing & rendering "body loaded"?
  2. Why if i remove onload handler from img element the reponse is as expected - "body loaded" and the page isn't blocked.
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
293 views
Welcome To Ask or Share your Answers For Others

1 Answer

Simply put, calling document.write() after DOM ready causes it to overwrite the existing DOM.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...