Unobtrusive JavaScript

When JavaScript was initially used, it was designed to be inserted directly into the HTML code as can be seen in this example:
<a id="button" href="#" onclick="alert(’Hello World’)">Click Me</a>  

This made it difficult to see what was happening as the JavaScript code was mixed up with the HTML. It also meant that the code was tightly coupled to the HTML, so any changes in the HTML required that the JavaScript code would also need changing to stop it breaking.
It’s possible to keep the JavaScript code on its own away from the HTML by placing it inside its own <script> tags, like so:
<script>
    button = document.getElementById (’button’)
    button.addEventListener ("click", function () {
        console.log ("Hello World!") ;
        };
</script>
  

Unobtrusive JavaScript is when the JavaScript code is kept completely separate from the HTML and CSS, preferably in its own file. This can be linked to using the same script tag and the src attribute to specify the file to link to:
<script src="js/scripts.js"></script>  

The JavaScript code would then be placed in a file called scripts.js.


Avoid Using Self-closing Tags
If you’ve used XML or XHTML, you might have come across self-closing tags such as this script tag:
<script src="js/scripts.js" />  
These will fail to work in HTML5, so should be avoided. 

You may see some legacy code that uses the language attribute:
<script src="js/scripts.js" language="javascript"></script>  

This is unnecessary in HTML5, but it will still work. 

In a similar way, the CSS should also be kept in a separate file, so the only code in a web page is the actual HTML. This is considered best practice and is the approach we’ll be using in the book.

0 Response to "Unobtrusive JavaScript"

Post a Comment