↑
Main Page
Inline code versus external files
To externalize the
sayHi()
function into a file named
external.js
, you copy the function text itself
(Figure 5-1).
Figure 5-1
Then the HTML code can be updated to include the external file:
<html>
<head>
<title>Title of Page</title>
<script language=”JavaScript” src=”external.js”></script>
</head>
<body>
<!-- body goes here -->
</body>
</html>
Inline code versus external files
When should you write code inline versus writing the code in an external file? Although no hard
and fast rules exist about when to use either method, the general consensus is that large amounts of
JavaScript should never be included inline for a number of reasons:
?
Security
— Anyone can see exactly what the code is doing just by viewing the source of the page.
If a malicious developer examines the code, he might find security holes that could compromise
the site or application. Additionally, copyright and other intellectual property notices can be
included in external files without interrupting the flow of the page.
No rules exist about what you can include in a single JavaScript source file, meaning
that you are free to include any number of class definitions, functions, and so on, in
a single file.
external.js
function sayHi() {
alert("Hi");
}
127
JavaScript in the Browser
08_579088 ch05.qxd 3/28/05 11:37 AM Page 127
Free JavaScript Editor
Ajax Editor
©
→