JavaScript 101

Now that you’ve learned a bit about JavaScript and why it exists, it’s time to dive in and start creating your first real script.

The <script> Element

Every script starts with a <script> block you slot somewhere into an HTML document. Really, you have only two options:

  • The <body> section. Put scripts you want your browser to run right away in the <body> section of your HTML. The browser runs your script as soon as it reaches the <script> element. If you put your script at the beginning of the <body> section, your browser processes the script before it displays the page.

    Tip

    Usually, JavaScript fans put their scripts at the end of the <body> section. That way, you avoid errors that might occur if you use a script that relies on another part of the page, and the browser hasn’t read that section yet. Because browsers read an entire page quickly, these scripts execute almost immediately.

  • The <head> section. If you place an ordinary script in the <head> section of your HTML document, it runs immediately, before the browser processes any part of the markup. However, it’s more common to use the <head> section for scripts that contain functions (see Functions). Functions don’t run immediately—instead, you summon them when your visitor takes some kind of action on a page, like moving a mouse.

Note

You can place as many <script> blocks in a web page as you want.

A typical script block consists of a series of programming instructions. To get a handle on how these instructions work, consider ...

Get Creating a Website: The Missing Manual, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.