Why is it generally not considered good practice to use document.write
in Javascript? I know it is not the most elegant or best way to do it, but are there any true errors with it? Is it ever ok? And in what case would it be better than inner.HTML
I understand that it will rewrite the document, if used after the loading. However, should I be using innerHTML
even if I am trying to rewrite the document? If so, why?
I know some have asked if I even looked at the related questions before posting; I did. But I did not find anything satisfactory.
yeah, calling document.write after the document has finished loading will wipe the document. Fire up your console, and do a
document.write("test")
call. The page will get overwritten with this new content. Except maybe for setting iframe innerHTML in a single step, never usedocument.write
.As a good pratice, sometimes we have information on the client side and using javascript we write these informations in
div
andspan
elements because they are in the right position of the html layout. And as the guys said,document.write
does not work with xhtml.One reason can be that
document.write
does not work in XHTMLAlso
document.write
only works while the page is loading; If you call it after the page is done loading, it will overwrite the whole page ie, after your document has been full rendered and closed, usingdocument.write()
will clear your current document and start a new one, wiping out all previous content.When used correctly, it's fine, but of very limited use.
You can't use it in XHTML, but I would recommend not using XHTML anyway unless you have a really, really good reason to.
The problem comes when you call
document.write
after the initial page load is complete. During page load is fine, but afterward, it causes an implicitdocument.open
, which clears the document from the window and starts fresh.Using
document.write
also means you can't demand-load your scripts or use theasync
ordefer
attributes on your script elements.Finally, I usually recommend putting your JavaScript in a separate (single) JavaScript file at the very end of the document (just before the closing
</body>
tag). If you want to usedocument.write
to output to the page, you'd have to include that script file higher up or use code directly within the HTML, neither both of which I recommend against.So since it's of such limited use compared with other methods, it's best to get proficient with the other methods.
Because it replaces entire document. In 99% of cases you just need to replace content of some specific elements.
document.write does have it uses - for example when you need to write an executable script to a newly created document.
From the MDN :
In short : code that must be executed past the initial
load
(for example in an event handler) can't include adocument.write
or they trigger a replacement of the whole document.