Monday, September 3, 2018

Why is document.write() a bad coding decision in JavaScript?

If you want to send content to a browser, there are many options. But one of them that you should avoid is document.write(), which may appear as...

document.write("<html><body>Hello!</body></html>");

This is considered poor form for a number of reasons.

First, it completely overwrites all content on the page with whatever is given to the write() function. So, if you have any other HTML on the page, it will disappear.

That means that all future coding and development needs to be done with this document.write("") function, and that's just an unnecessary complication.

The real problem is that it's difficult to work with. A coder using document.write()'s all over their script will take much longer to finish than one who is using proper DOM manipulations (like using element.innerHTML(), jQuery's append(), etc.).

There are also technical problems: XHTML does work with document.write("").

There are also security problems: Google Chrome will refuse to run document.write("") if it contains anything in the write("") which was from a POST or GET query, or if it suspects that any cross-site scripting injection is taking place.

There are also performance problems: Google Chrome itself will give the warning that document.write("") may slow down your webpage by "tens of seconds," according to the Google Developers blog (https://developers.google.com/web/updates/2016/08/removing-document-write).

No comments:

Post a Comment