Categories
JavaScript Tutorials

How and Where to Add JavaScript to a Web Page

Web browsers are built to understand HTML and CSS and convert those languages into a visual display on the screen. The part of the web browser that understands HTML and CSS is called the rendering engine. 

But most browsers also have something called a JavaScript interpreter. That’s the part of the browser that understands JavaScript and can execute the steps of a JavaScript program. The web browser is usually expecting HTML, so you must specifically tell the browser when JavaScript is coming by using the <script> tag.

The <script> tag is regular HTML. It acts like a switch that in effect says “Hey, web browser, here comes some JavaScript code; you don’t know what to do with it, so hand it off to the JavaScript interpreter.” When the web browser encounters the closing </script> tag, it knows it’s reached the end of the JavaScript program and can get back to its normal duties.

Much of the time, you’ll add the <script> tag in the web page’s <head> section, like this:

<html>
  <head>
    <title>My Web Page</title>
    <script type="text/javascript">
    </script>
  </head>
</html>

The <script> tag’s type attribute indicates the format and the type of script that follows. In this case, type=“text/javascript” means the script is regular text (just like HTML) and that it’s written in JavaScript.

If you’re using HTML5, life is even simpler. You can skip the type attribute entirely:

<html>
  <head>
    <title>My Web Page</title>
    <script>
    </script>
  </head>
</html>

You then add your JavaScript code between the opening and closing <script> tags:

<html>
  <head>
    <title>My Web Page</title>
    <script>
      alert('hello world!');
    </script>
  </head>
</html>

You’ll find out what this JavaScript does in a moment. For now, turn your attention to the opening and closing <script> tags. To add a script to your page, start by inserting these tags. In many cases, you’ll put the <script> tags in the page’s <head> in order to keep your JavaScript code neatly organized in one area of the web page.

However, it’s perfectly valid to put <script> tags anywhere inside the page’s HTML. In fact, as you’ll see later in this chapter, there’s a JavaScript command that lets you write information directly into a web page. Using that command, you place the <script> tags in the location on the page (somewhere inside the body) where you want the script to write its message.