You need JavaScript to define how your web pages interact with end-user. In this tutorial, you’ll learn the different methods to link a JavaScript code to an HTML file.

You can link JavaScript code to an HTML document using <script> tag:

  • Write JavaScript code within an HTML document
  • Link an external JavaScript file to an HTML document

Let me describe to you both methods in detail

How to write JavaScript code within an HTML document

The HTML <script> tag allows you to write the Javascript code within the <head> or <body> sections of the HTML document.

Here comes a simple example where the Javascript code exists within the <body> section of an HTML document.

<!DOCTYPE html>
	<head>
		<title> A Sample Web Page </title>
	</head>
	<body>
      <button type ="button" onClick="displayAlert()"> Click </button>
	    <script>
				 function displayAlert() {
						alert("The button has been clicked.");
				 }
     </script>
  </body>
</html>

You can link external JavaScript files with extension .js, to an HTML document using the same HTML tag <script>. The way you do it a bit different as now you’ll have to provide a path to the script using the src property.

Let’s consider we have an external Javascript file, testscript.js

function displayAlert() {
	alert("The button has been clicked.");
}

You can link the JavaScript file, testscript.js to an HTML file by adding the property src="testscript.js" to the <script> tag.

<!DOCTYPE html>
	<head>
		<title> A Sample Web Page </title>
	</head>
	<body>
      <button type ="button" onClick="displayAlert()"> Click </button>
	    <script src="testscript.js"></script>
  </body>
</html>

We can link multiple files to an HTML document using multiple <script> tags.

Few extra details on JS in HTML

You’ve learned how to link JavaScript code to an HTML file. Here are two important factors you should consider moving forward:

  • Writing or linking JavaScript code at the bottom of the <body> section helps the browser to load the web page faster.
  • Linking external Javascript files to HTML helps in better organization and management of code. This also improves the response time of your webpage through file caching.

Read more JavaScript tutorials or Learn Full-Stack JS from scratch!