2. JavaScript: How to Add in HTML

There are two different ways to add javaScript in HTML. One is to embed your code into your HTML and second is add javaScript code in separate file and call it in your HTML. We can start from adding script directly in HTML file and you will see the second method in article 9, External JavaScript Files.

Script starts with <script type=”text/javascript”> and ends with </script>. What ever will come in between, will be your javaScript code.

<script type="text/javascript">
   function myFunction(){
      alert("Hello from my function");
   }
   myFunction();
</script>

 

Insert this script in HTML file. Copy the following code and save your helloworld.html file. Drag helloworld.html file in your browser and you will see alert from javaScript.

<html lang="en">
	<head>
		<meta charset="utf-8" />
		<title>Understand-Programming</title>
	</head>
	<body>

		<h1> Welcome to Javascript</h1>
		<script type="text/javascript">
			function myFunction(){
				alert("Hello from my function");
			}
			myFunction();
		</script>
	</body>
</html>


Where to add JavaScript

It is very common question that where to add javaScript in HTML file and answer is you can add where ever you want but good place is in bottom of the body tag.

The reason is, at the beginning  you will be writing very simple and small code of javaScript. But when the website will grow, the code will be long and complexed, which can take long time for execution. If you will add your script at the beginning of your HTML file, web page content will not load until script execution will not finish but if you will add your script at the bottom of your web page, the web content will load first and script execution will start later. By using this technique, end user will not feel any problem.

Just for experiment change the location of javascript from <body> tag to <head> and notice the difference.

<html lang="en">
    <head>
        <meta charset="utf-8" />
            <title>Understand-Programming</title>
            <script type="text/javascript">
                function myFunction(){
                    alert("Hello from my function");
                }
                myFunction();
            </script>
    </head>
    <body>
        <h1> Welcome to Javascript</h1>
    </body>
</html>

 

Download file from GitHub for more examples