Anjan Dutta
How to include JavaScript in HTML
How to include JavaScript in HTML
Created On: 02/10/2021
There are three ways of including Javascript in HTML code.
- In file
- Inline
- Import
In file
In this method, we write the javascript code in the <head>
section of the html. We enclose the code in script tags.
<html> <head> <title></title><script>function helloWorld() { console.log('hello world');}</script> </head> <body> <button onclick="helloWorld()"> Click Me! </button> </body></html>
Inline
In this method, we write the complete code in html tag directly.
<html> <head> <title></title> </head> <body> <button onclick="console.log('hello world');"> Click Me! </button> </body></html>
Import
In this method, we write the javascript code in an external file and import that file into the html code by defining the file path as a source attribute in the script tag.
script.js
function helloWorld() { console.log('hello world');}
<html> <head> <script type="text/javascript" src="script.js"/> <title></title> </head> <body> <button onclick="helloWorld()">Click Me!</button> </body></html>