If you use document.write as a part of the 'onload' event of the window object then it will erase any existing content in that page and insert only the one you've inserted through the document.write method.
But if you use document.write before the completion of the page rendering then the information you insert using document.write will be inserted in your page along with other content the page already has.
Eg 1:
Code:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title> </title>
<style type="text/css">
</style>
<script type="text/javascript">
window.onload = function(){
document.write('Hello World ');
}
</script>
</head>
<body>
<div>This is a test </div>
</body>
</html>
If you open the page you can only view 'Hello World' in your page as we've used document.write method to insert some information in to a page which has rendered completely.
Eg 2:
Code:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title> </title>
<style type="text/css">
</style>
<script type="text/javascript">
document.write('Hello World ');
</script>
</head>
<body>
<div>This is a test </div>
</body>
</html>
If you open the above page in browser it will show 'Hello World' then a line break and 'This is a test', linebreak comes because we've used <div> element to wrap 'This is a test'.
You can insert a <script> element within <head> or <body>. But normally developers use the <head> section.
It is always better if you not mingle your markup with your JavaScript section as it will make reading of the web page more difficult from a developer's point of view so what a developer do is :
- If you have large volume of JavaScript in a page then they'll save it as a different .js file and include that file in to the web page like the following manner
<script type="text/javascript" src="myfuns.js"></script>
"myfuns.js" is a file which contains only JavaScript code.
If you want to improve the look and feel of the information in the web page again you can append the style information within the markup or can have a CSS file and include that like the following manner:
<link rel="stylesheet" type="text/css" href="mystyles.css" />
After including the CSS file in your web page you can apply the classes, IDs, etc in your page without messing your (X)HTML markup.
Bookmarks