Unobtrusive JavaScript

The following HTML code shows the basics of modern javascript programming :

<html>
<head>
<script type=”text/javascript” src=”helloworld.js”></script>
</head>
<body>
<p id=”hello”></p>
</body>
</html>

The concept is to keep the javascript separate from the HTML of the web page and to just use a script tag in the head section of the webpage to link the two together. An id tag is used to identify the part of the body of the web page that should be updated with javascript.

The javascript code is shown below :

function sayHello() {
document.getElementById(‘hello’).innerHTML = ‘Hello World’;
}
window.onload = sayHello;

In the past the function document.write() was used for this purpose, but this is “bad form” and not valid xhtml code. To adhere to strict xhtml code, then it would be better to create elements using document.createElement and element.appendChild (and other native DOM node manipulation functions). For inserting text into an existing element, innerHTML is still acceptable code (and completely cross-browser). The “all DOM” way requires a lot of extra code, is slower, harder to maintain than simpler method and it needs more bandwidth.