Lesson 3.2. JavaScript Hello World

JavaScript is sent from the server (like HTML), but it runs in the browser. It is said to be a client-side language, as opposed to a server-side language like PHP or NodeJs. The easiest way to write its first lines of JavaScript is to insert it in the same file as the HTML.

JavaScript and HTML

To insert JavaScript into HTML, we use a dedicated <script></script> tag. For example, the following code displays a pop-up with the message Hello World.

<script>alert ('Hello World');</script>

JavaScript can be inserted in the page header (in the <head></head> tags). In this case, it runs before the page content is displayed. Here is an example:

<html>
  <head>
    <!-- Le JavaScript est inséré dans l'en-tête HTML -->
    <script>alert ('Hello World');</script>
  </head>
  <body>
    <h1>My first JavaScript code</h1>
  </body>
</html>

It is also possible to insert the JavaScript in the body of the HTML page (in <body></body> tags). This is generally the preferred solution because:

<html>
  <head>
  </head>
  <body>
    <h1>My first JavaScript code</h1>

    <!-- Le JavaScript s'exécute après le HTML -->
    <script>alert ('Hello World');</script>

  </body>
</html>

External JavaScript

The JavaScript can be in an external file. For example, a file myScript.js file would contain the following code:

alert ('Hello World');

To tell the browser to fetch the file, the following syntax is used in HTML:

<script src="monScript.js"></script>

As for the internal JavScript, the position of the <script> tag determines its order of execution. Again, in order not to slow down the display, it is better to place it before the </body> closing tag.

Exercise

In the following HTML code, add a line that allows you to insert the script that is located at the address https://lucidar.me/fr/web-dev-class/files/premierJavaScript.js

<html>
  <head>
  </head>
  <body>
    <h1>External JavaScript</h1>

    <!-- Add external JavaScript here -->

  </body>
</html>

Note that this type of alert is quite unpleasant for the user. One should avoid using the alert() function in JavaScript.

Quiz

Where can we place the JavaScript?

Check Bravo! JavaScript can be placed in the HTML or in an external file. Try again...

Where the JavaScript runs?

Check Bravo! The JavaScript runs in the user's browser. Try again...

JavaScript is ... ?

Check Bravo! The JavaScript is sent by the server (along with the HTML), but executed on the client. Try again...

Which tag allows you to insert JavaScript into HTML?

Check Bravo! The </script> tag allows you to run different languages including JavaScript. Try again...

Where to place the JavaScript to prevent slowing down the page display

Check Bravo! If the JavaScript is at the end of the page body, it will run after the page is displayed. Try again...

See also


Last update : 10/03/2022