In web programming, JavaScript is used to perform actions on the browser side which enhance the HTML page being served. The major browser platforms support JavaScript documents, and follow a specific standard guaranteeing that all JavaScript code is executed in the same fashion. One of the ways in which the client side processing of HTML documents can be enhanced is by introducing text into the document using the JavaScript document.write command.
The basic form for this command is as follows:
The above snippet would insert Insert Text at the point that the JavaScript is executed.
The document.write command must be carried out during the loading of the page. So, if it is attached to any event that executes after the page has loaded, then the whole page will be replaced with the contents of the document.write command.
This can, however, be useful in creating pages that have multiple steps, so long as the data needed to be shared across pages is passed correctly between them. Ordinarily, however, this is not the case.
Inside the document.write command, any HTML can be specified, as well as plain text. So, for example, the following would be perfectly acceptable:
The document.write command can be used inline, or inside a script contained within the <head> part of the HTML document. As with all JavaScript, if this is the case, then it is best to contain it within a specific function that is called from within the body of the document, or from another function in the head.
To use it inline, the following should be used:
There will be no break inserted between the regular HTML and the inserted text.
Strings of values can be concatenated within the document.write command, usually specified as variables:
This example shows one of the reasons why the JavaScript document.write command is so useful.
It is very useful to be able to insert conditionally chosen snippets of HTML, for example:
Above all, the document.write command allows the web programmer to introduce dynamic functionality without needing to use a web host which provides server side scripting. However, the reader should always remember that the web site visitor only needs to view the source of the web page to review all the JavaScript code, so it is not good to use for solutions that require security or protected source code.