Saturday, November 5, 2022

Creating the JavaScript Program File

The first step in running a JavaScript program is creating a file that contains the definitions of the functions, along with comments that give human readers a better understanding of what the program does. 
• Here, for example, is the complete HelloWorld.js file:

/* * File: HelloWorld.js * ------------------- 
* This program displays "hello, world" on the console. It
* is inspired by the first program in Brian Kernighan and 
* Dennis Ritchie's classic book, The C Programming Language. */
 
function HelloWorld() {
     console.log("hello, world"); 
}

Creating the HTML File (Version 1)

  • A simple HTML file that loads the HelloWorld.js program looks like this:
<!DOCTYPE html>
<html>
   <head>
      <title>Hello World</title>
      <script type="text/javascript" src="HelloWorld.js"></script>
</head>
<body onload="HelloWorld()"></body>
</html>

  • This file asks the browser to load the file HelloWorld.js and then call the function HelloWorld once the page is loaded.
  • The problem with this strategy is that it is hard "to find out where your output went" as Kernighan and Ritchie advise. 

Creating the HTML File (Version 2) 


• The output from the console log appears in different places in different browsers and usually requires the user to take some explicit action before it is visible. 
• To make the console log easier to find, we have provided a library called JSConsole.js that redirects the console log to a much more visible area of the web page.

<!DOCTYPE html>
<html>
<head>
<title>Hello World</title>
<script type="text/javascript" src="JSConsole.js"></script>
<script type="text/javascript" src="HelloWorld.js"></script>
</head>
<body onload="HelloWorld()"></body>
</html>

No comments:

Post a Comment