By using this site you agree to the use of cookies by Brugbart and our partners.

Learn more

An Introduction to JavaScript

This shows how to use JavaScript in HTML. Brugbarts Introduction to JavaScript, shows how to include JavaScript in pages.

Edited: 2011-07-25 14:24

JavaScript is a client-sided scripting language, which means that its executed entirely in the visitors browser. Unlike PHP which is executed on the Server.

What to use it for

JavaScript has many practical uses. While you should generally avoid using it for layout purposes, it has many other uses, which can both enrichen the user experience, and lower the load on your server.

User experience

JavaScript is used to create WYSIWYG editors, amongst other things. Such as those you will find on many forums when posting.

It is also used to set and read cookies, perhaps one of its most common uses.

Technical benefits

There are cases where JavaScript can be used, to reduce server load. You should however not replace server-sided validation of forms, with JavaScript. But it can be used to prevent invalid data, before its submitted, which would free up some CPU on the server.

How to include JavaScript

Embedding Example

There are two ways that you can include JavaScript in your pages, the first mentioned is by embedding it directly in the head section, using the HTML script element.

<!DOCTYPE html>
<html lang="en-US">

  <head>
    <title>My first Website</title>
  </head>

  <body>
    <script type="text/javascript">
      document.write("<p>This is my first JavaScript!</p>");
    </script>
  </body>

</html>

Brugbart Vision!

The JavaScript write method, is used to write HTML content, and will overwrite the current page.

External files Example

The second method is also using the HTML Script element. But this time we take the script, save it as script.js and then we type the filename in an src attribute

Note. See Absolute and Relative paths, to learn how to define file paths.

<!DOCTYPE html>
<html lang="en-US">

  <head>
    <title>My first Website</title>
  </head>

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

</html>

Brugbart Vision!

The content of the script.js file should be as below.

document.write("This is my first JavaScript!");

The best inclusion method

It would depend on the situation. But generally its best to keep your scripts in external files, when the same script is used on multiple pages.

This is to take advantage of caching in the browser, which eliminates the need to download these files every time a page using them is requested.