Getting Started with JavaScript

How can you add JavaScript to a web page?

There are three methods to add JavaScript in a web page.

  • Embed the JavaScript code between a pair of <script> and </script> tag.
  • Create an external JavaScript file with the .js extension. Load it within the page through the src attribute of the <script> tag.
  • Insert the JavaScript code directly inside an HTML tag using the special tag attributes such as onclick, onmouseover, onkeypress, onload.

Let's discuss these methods in detail

Embed the JavaScript Code: Embed the JavaScript code between a pair of <script> and </script> tag. The <script> tag instructs the web browser to interpret the contained statements as executable script.

Example

.html
<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Embedding JavaScript Code</title>

</head>

<body>

<script>

var j = "Introduction to JavaScript";

document.write(j);

</script>

</body>

</html>

Call External JavaScript File: Create an external JavaScript file with a .js extension and then call that file in the document using the src attribute of the <script> tag.

This method proves beneficial when you want to have the same scripts across different documents. It cuts down the need to perform the same chores repeatedly, thereby ensuring easy maintenance of your website.

.js

function sayIntro() {
alert("Introduction to JavaScript!");
}
// Call function on click of the button

document.getElementById("myBtn").onclick = sayIntro;

Name the above file as 1.js. Call the above file in a web page using the <script> tag.

Example

.html
<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Including External JavaScript File</title>    

</head>

<body>&#x9;

<button type="button" id="myBtn">Click Here</button>

<script src="js/1.js"></script>

</body>

</html>

When the web browser downloads the external JavaScript file, it gets stored in the cache. This eliminates the need to download repeatedly.

Insert the JavaScript code directly inside an HTML tag: Place the JavaScript code in the HTML tags using special tag attributes such as onclick, onmouseover, onkeypress, onload.

Example

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Inlining JavaScript</title>

</head>

<body>&#x9;

<button onclick="alert(‘Introduction to JavaScript')">Click Here</button>

</body>

</html>

What is the ideal position of the <script> tag inside the HTML document?

The ideal position of the <script> tag lies at the end of the body section. Ensure it is placed before the closing </body> tag. This ensures easy loading of web pages.

What is the difference between client-side and server-side scripting?

The client-side scripts run on the web browser while the server-side scripts run on the web server. The client-side scripts are faster than the server-side scripts. This is because the server-side scripts run on the remote computer.