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

Categories

0 votes
292 views
in Technique[技术] by (71.8m points)

javascript - Document.write method questions

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

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

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...