Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development > PHP/MySQL/Scripting

  • Print
  • + Share This
This chapter is from the book

Apply JavaScripts Wisely

JavaScripts can be included in an (X)HTML document in any of four ways:

  • In an external file

  • Between a pair of <script>...</script> tags

  • In an event handler

  • After the javascript: pseudo-protocol in an URL

Let's use our minimal Mondrian to demonstrate them all:

<!DOCTYPE html 
   PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   " ">
<html xmlns="" xml:lang="en" lang="en">
<title>Piet Mondrian's Home Page</title>
<script src="/scripts/foo.js" defer="defer" type="text/javascript"></script>
<script type="text/javascript">
   var foo = 1;
   <h1>Piet Mondrian: Abstract Impressionist</h1>
   <p>Mondrian was one of the great abstract masters...</p>
   <p><a onmouseover="window.status='Mondrian Home Page'; return true;"; 
href=""></a></p> <p><a href="'')"></a></p> </body> </html>

In honor of Mondrian and expediency, let's focus squarely on the first two options. Event handlers can be used to link behavior to elements (ideally with functions), but the javascript: pseudo-protocol should be avoided as the only reference of a link. The 11 percent of people without JavaScript won't be able to access this content.3 This is not exactly user friendly.4 A number of sites rely on JavaScript—even government sites that should be easily accessible like

Here's the syntax of the script element:



Defines an executable script




<script type="text/javascript" src="/scripts/foo.js"></script> <script type="text/javascript" src="/f.js" defer="defer"></script> /* optimized */

End tag:

</script>, not optional


<noscript>alternate content</noscript>

Used in:

<head>, <body>

  • + Share This
  • 🔖 Save To Your Account