开发者

Why does document.write hurt web performance?

开发者 https://www.devze.com 2023-01-08 19:14 出处:网络
I\'m told that document.write should be avoided in web page since it hurts web page performance. But what is the exact reaso开发者_开发知识库n?document.write() itself doesn\'t seem to be very harmful

I'm told that document.write should be avoided in web page since it hurts web page performance. But what is the exact reaso开发者_开发知识库n?


document.write() itself doesn't seem to be very harmful to page performance in most browsers. In fact, I ran some tests at DHTML Kitchen and found that in Firefox, Opera and Chrome, document.write() was actually faster on the first load, and comparable in speed of standard HTML on subsequent refreshes. Internet Explorer 8 was the exception, but it was actually faster than the other browsers at rendering the HTML (surprisingly).

As Guffa's answer points out, and what I was building up to, the actual performance issues come from inline scripts themselves. Content rendering can only continue when an inline script has finished executing, so if you have a complexe routine inside an inline script you can noticeably halt your page's loading for the end user. That's why waiting for onload/DOMReady and using DOM manipulation is preferred.

It's especially unwise to use document.write() after the document has finished loading. In most browsers, using document.write() after document load also implies document.open(), which will wipe the current HTML off the screen and create a new document.

That doesn't mean that document.write() doesn't have its uses, it's just that most developers use it for the wrong reasons. Real problems with document.write() include:

  • You can't use it in documents served as XHTML (for browsers that correctly parse XHTML as XHTML).
  • Overwrites the entire page when used after DOM parsing has completed.
  • Adds content to the page that isn't accessible to browsers with JavaScript disabled (although <noscript> is sometimes a valid workaround here).
  • More difficult to maintain than static HTML.


If you have scripts that run in the middle of the page, the browser has to wait for the script to finish before it can continue to parse the rest of the page.

To make your page appear fast, you want the browser to parse the page as soon as possible so that it can be displayed to the user, and after that you can apply the extra functionality that your scripts add.


I think there are some reason why it should be avoided.

but what you mean is, that if you have somewhere in your html code a

<script>
 document.write('mystuff')
</script

one of the problem is, that bevore the browser can display your website, it has to load the Javascript interpreter. if you would start your javascript only by body.onLoad then it can display the whole website to the user, and then run your javascripts... therefore

the subjective loading time is faster :-)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号