I'm told that document.write should be avoided in web page since it hurts web page performance. But what is the exact reason?
write() are encountered, DOM construction must be halted because the browser has to wait for such resources to download, parse, and execute. If the script then dynamically injects another script, the browser is forced to wait even longer for the resource to download. Using document.
Since document. write() is always available (mostly) it is a good choice for third party vendors to use it to add their scripts. They don't know what environment you're using, if jQuery is or isn't available, or what your onload events are. And with document.
write() is parser-blocking. Scripts with the ' async ' or ' defer ' attributes will still execute. The script is not hosted on the same site. In other words, Chrome will not intervene for scripts with a matching eTLD+1 (e.g. a script hosted on js.example.org inserted on www.example.org).
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:
<noscript>
is sometimes a valid workaround here).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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With