It's extremely easy to mix JavaScript into HTML, in a variety of ways, to allow your new found JavaScript skills to bring your web pages to life - as this tutorial demonstrates.
The simplest way to add JavaScript into HTML is to use the <script> tags - as shown below...
<html>
<head>
<title>JavaScript Test</title>
</head>
<body>
<script>
/* This JavaScript is ran whilst the page is being rendered... */
console.log("Hello world!");
document.querySelector("body").textContent = "Hello (again)";
</script>
</body>
</html>
This makes the script within the tags get run as the page is rendered.
This approach is not recommended for anything larger than simple testing - for real world web pages/websites, the approach described next should be adopted instead...
The best way to link JavaScript into HTML is to use the <script> tags to link to external files. The file path is relative to your HTML document (just like the linking of external CSS files). An example of this in action is shown below...
<html>
<head>
<title>JavaScript Test</title>
</head>
<body>
<script src="path/to/the/script.js"></script>
</body>
</html>
<script> links should be located at the end of the document. This is so that the HTML can be rendered properly first, before JavaScript is executed.
Yes! Scripts which refer to variables or functions defined in other scripts must be linked before scripts that rely on them.
By default, everything in JavaScript has a global scope once included - for this reason, variables and functions are usually put within objects, to stop names from colliding easily, and to provide a basic namespace system.
No - not natively. However, a library called RequireJS makes this possible (and is coincidentally used within this website).
In HTML versions lower than HTML5, the <script> tag requires the type="text/javascript" attribute to be included. In HTML5, this attribute's information is assumed automatically, and it is not required.