Archive for August 8, 2007

How to Include an External JavaScript File

Posted in JavaScript on August 8, 2007 by Joey

To include an external JavaScript file in a file, use the script tag.

<script src='../filename.js'></script>

The src attribute refers to the path where the included file resides. The file specified is a file that contains JavaScript only and has no script tags.

Note that the end script tag immediately follows the beginning script tag.

Why use the script tag to include a JavaScript file instead of embedding the JavaScript directly within the HTML file? A number of advantages are listed below:

1) Allows for the separation of presentation and scripting.
2) Files can be included in an HTML page from other web servers.
3) Provides for modular and reusable code. For instance, a function can be created once, placed in the .js file and then used among multiple pages.
4) Placing JavaScript in it’s own file causes the browser to cache the JavaScript when it is used among multiple pages.

How to Determine the Operating System of the Client Machine with JavaScript

Posted in JavaScript on August 8, 2007 by Joey

To determine the operating system of the client machine on which a browser is executing JavaScript, use the appVersion property of the JavaScript navigator object, as demonstrated in the following example:

document.write(navigator.appVersion);

The information given in this property can be extrapolated, albeit in a somewhat rudimentary way, to determine whether the operating system is Windows or Macintosh, as shown below:

var strOS = navigator.appVersion;

if (strOS.toLowerCase().indexOf('win') != -1)
document.write('Windows');
else if (strOS.toLowerCase().indexOf('mac') != -1)
document.write('Macintosh');

Related articles:
JavaScript String Object indexOf Method