The Placement of JavaScript Codes - JavaScript: Academy: The Stress Free Way to Learning JavaScript Inside & Out (2016)

JavaScript: Academy: The Stress Free Way to Learning JavaScript Inside & Out (2016)

Chapter 3. The Placement of JavaScript Codes

You can place JavaScript codes in any part of an HTML file. However, the recommended areas for keeping JavaScript codes inside an HTML document are:

· In the <head> </head> area

· In the <body> </body> area

· In the <head> </head> and <body> </body> areas of the document

· Inside an external document

This chapter will discuss each of these areas.

Placing Your Code in the <head> </head> Area

This is the ideal area if you want your scripts to run during specific events (e.g. when the user clicks on a button). The sample code below will show you how to save codes in this area.

If entered correctly, the code will show you this:

Placing Your Code in the <body> </body> Area

In general, you should place a JavaScript code in the <body> section if you want it to produce content as the webpage loads. Here, you don’t have to define any function using JavaScript. Here’s an example:

That code generates the following result:

Placing Your Code in the <head> </head> and <body> </body> Areas of the Document

You also have the option to place your JavaScript code in both the <head> and <body> areas of the HTML file. Analyze the following example:

If you entered the code properly, opening the HTML file will give you this:

Placing the Code in an External File

While using JavaScript, you’ll surely find many situations where you have to use the same codes on different webpages. Typing the same code repeatedly can be boring and time-consuming. Fortunately, you can simply save your JavaScript codes in an external file. Then, you just have to link that file to the webpages that need the identical codes.

In using this method, you should use a script tag and the src attribute. Check the example below:

This method requires you to write your JavaScript code inside a text file and save it using“.js” as the extension (e.g. example.js).

Let’s try a simple exercise. Copy the code below into a text file and save it as“filename.js”. Then, utilize the sayHello function of your HTML document after adding the filename.js file.