Adding JavaScript to Your Web Pages

Tuesday, April 3, 2012

Adding JavaScript code to a web page is straightforward and simple. JavaScript programs contained within an HTML page are referred to as scripts. When you want to add JavaScript code to a web page, you contain the code within the <script> element. When a web browser comes across this element, the Web browser knows that that the scripting engine must interpret the commands within the element. The type attribute of the script element tells the browser which scripting language and which version of the scripting language is being used. For example, you assign a value of "text/javascript" to the type attribute to indicate that the script is written with JavaScript. Here is an example:

<script type="text/javascript">
...code... ;

Where do I place these scripts?

There is no limit to the number of scripts you can have in your web document. Scripts can be located within head and body elements, even at the same time. However, if possible you should place all of your scripts in the head section, just before the closing head tag. If you place scripts within the body section, the scripts should be placed at the very bottom, just before the closing body tag.

External JavaScript Files

JavaScript can also be placed in external files. This is a common approach. External JavaScript files often contain code to be used on several different web pages. This way, you only have to have the JavaScript code defined once, in an external file which can be used by many different pages. External JavaScript files should be saved with the file extension of .js. To reference an external script, simply point to the .js file in the "src" attribute within the <script> element.  Here is an example:

<script type="text/javascript" src="filename.js"></script>

Generally, JavaScript scripts within an HTML page will be executed when the page loads. This may not be the behavior that we would prefer. In some cases, we would want to execute the JavaScript code when an event occurs, such as when a user clicks a button. For these types of scenarios we would need to place the JavaScript code within a function. We will learn more about JavaScript functions in the upcoming tutorials.

Did you find the page informational and useful? Share it using one of your favorite social sites.

Recommended Books & Training Resources

JavaScript and jQuery: The Missing Manual HTML CSS and JavaScript Editor Professional JavaScript for Web Developers