Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is document.write considered a "bad practice"?

Tags:

javascript

I know document.write is considered bad practice; and I'm hoping to compile a list of reasons to submit to a 3rd party vendor as to why they shouldn't use document.write in implementations of their analytics code.

Please include your reason for claiming document.write as a bad practice below.

like image 917
FlySwat Avatar asked Apr 29 '09 15:04

FlySwat


People also ask

Is document write deprecated?

No. It's just most often considered bad practice and almost as misused as eval . Read: Why is document. write considered a 'bad practice'?

Why we use document write in JavaScript?

The write() method in HTML is used to write some content or JavaScript code in a Document. This method is mostly used for testing purpose. It is used to delete all the content from the HTML document and inserts the new content. It is also used to give the additional text to an output which is open by the document.

What does document write can be a form of eval mean?

write can be a form of eval means is: the syntax document. write relates to/ uses the eval function, an inbuilt js function. It is warning you not to use eval because there are risks associated with it.


2 Answers

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

like image 118
annakata Avatar answered Oct 04 '22 05:10

annakata


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

  1. It keeps the scripts small
  2. They don't have to worry about overriding already established onload events or including the necessary abstraction to add onload events safely
  3. 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.

like image 23
Peter Bailey Avatar answered Oct 04 '22 05:10

Peter Bailey