Why is document.write considered a "bad practice"?
There's actually nothing wrong with document.write
, per se. The problem is that it's really easy to misuse it. Grossly, even.
In terms of vendors supplying analytics code (like Google Analytics) it's actually the easiest way for them to distribute such snippets
- It keeps the scripts small
- They don't have to worry about overriding already established onload events or including the necessary abstraction to add onload events safely
- It's extremely compatible
As long as you don't try to use it after the document has loaded, document.write
is not inherently evil, in my humble opinion.
A few of the more serious problems:
document.write (henceforth DW) does not work in XHTML
DW does not directly modify the DOM, preventing further manipulation(trying to find evidence of this, but it's at best situational)DW executed after the page has finished loading will overwrite the page, or write a new page, or not work
DW executes where encountered: it cannot inject at a given node point
DW is effectively writing serialised text which is not the way the DOM works conceptually, and is an easy way to create bugs (.innerHTML has the same problem)
Far better to use the safe and DOM friendly DOM manipulation methods