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.
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>
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.
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.
Where can we place the JavaScript?
Where the JavaScript runs?
JavaScript is ... ?
Which tag allows you to insert JavaScript into HTML?
</script>
tag allows you to run different languages including JavaScript.
Try again...
Where to place the JavaScript to prevent slowing down the page display