1. How to Use JavaScript?

In this JS tutorial, we will learn how to use JavaScript code in our HTML documents. Basically, we need to include or attach the JavaScript code, to a web page, in order to make its content dynamic and change its behavior. In this ultimate and up-to-date JavaScript course, we will learn all the methods to include JS code in a web page.

1.1. Methods to Include JS

Basically, there are three main methods to add JavaScript code to a document. These methods are listed below.

  1. Inline Scripting
  2. Onpage / Internal Scripting
  3. External Scripting

Tutorial Contents:

  1. How to Use JS?
  2. Adding Inline JS Script
  3. Adding Onpage / Internal JS Script
  4. Linking External Script File
  5. Conclusion

2. JavaScript Inline Scripting

  • The very first method that we will discuss in this JS tutorial of how to use JavaScript is inline scripting.
  • If we look at the HTML event attributes course, we will notice that all those HTML5 attributes are related to JavaScript, and certainly, we can utilize them for inline JS scripting.
  • Most importantly, this inline JS script is only used for that particular HTML element to which that attribute is associated.
  • Thus, we cannot use that inline JS script for any other element.
  • If we want the same functionality for any other HTML element, we will have to repeat the process for the other element again.

Look at the following examples to understand the inline scripting method in detail.

Example 1

Open an Alert by clicking the button.

<button onclick="alert('Hello World!');">Click me</button&g;

Try in CodeLab

Example 2

Change the color of the document with the click of a button.

<a href="#" onclick=" document.body.style.color= 'skyblue'; ">Change Color</a>

Try in CodeLab

Example 3

Open the image in a new window upon clicking.

<img src="plane.jpg" onclick="window.open('plane.jpg', '_blank');" alt="A Flying Aeroplane" />

Try in CodeLab

2.1. Benefits of Using JS Inline Scripts

Apart from the drawbacks, there are some advantages or benefits of using inline scripts in JavaScript programming. Actually, there are certain places, where the use of inline JavaScript is advisable or beneficial. Below are the advantages of inline scripts.

Advantages of Inline Scripting

  1. Easy Implementation: While writing HTML markup, we can immediately add incorporate the inline script.
  2. Fast Loading: Since the inline JavaScript code is part of HTML, therefore it loads quickly as it does not have to make any additional HTTP request.
  3. Accessibility: Even if the JavaScript in the browser is disabled, the inline scripts are accessible as they are part of the HTML code.
  4. Easy Debugging: Being a part of the same document, debugging is easy and swift for the inline scripts.
  5. Flexibility: We can modify the page content and make it more dynamic by the use of inline scripts thus increasing the flexibility and customization of the UX.
  6. Dynamic Interaction: In order to make dynamic interactions, such as showing/hiding content, changing appearance, etc. the inline scripts are more useful in such context.

2.2. Why Inline Scripting is not Recommended?

There are several reasons why inline scripting is not recommended, and therefore, we should avoid this practice. Below are some disadvantages or reasons that should be kept in mind while adding the inline JavaScript code.

Drawbacks of Inline Scripting

  1. Security: Hackers can easily manipulate the inline scripts to inject malicious code into a website, which can compromise the security of the website.
  2. Maintenance: While there are plenty of pages with inline scripts on a website, it will be difficult to maintain those scripts as any change in the code will need to open each page separately.
  3. Reusability: If we include the inline scripts, it is difficult to reuse that code, and we need to rewrite that piece of code again to use it on other pages.
  4. Performance: The browsers do not cache the inline scripts, therefore, they will need to be downloaded each time the page loads, resultantly decreasing the speed and performance of the website.

3. JavaScript Onpage / Internal Scripting

  • In this topic, we will explain how to use JavaScript as an internal or onpage script.
  • Basically, the internal or onpage JavaScript code is present on the same page on which we need to use it.
  • Thus, the internal JS script loads along with the page it is needed for.
  • In order to include the internal or onpage JavaScript on a webpage, we use the HTML <script> tag.
  • The process is also explained in the HTML scripts tutorial.

Consider the subsequent instances to understand how to include the internal or onpage JavaScript code.

3.1. JavaScript in <head>

We can include the internal JavaScript within the <head> of the document. For this purpose, we will utilize the <script> tag.

In the below example, we placed a JS function inside the <head> of the document that changes the background and color of the HTML elements using the ID attribute.

JS in <head>

<!DOCTYPE html>
<html>
<head>
<script>
function changeColor() {
	var para = document.getElementById("main-para");
	para.style.backgroundColor = "yellow";
}
</script>
</head>
<body>

<div id="main-para">
Click the button to change the background of this element.
<button onclick="changeColor()">Change Color</button>
</div>

</body>
</html>

Try in CodeLab

3.2. JavaScript in <body>

We can place the internal JavaScript within the <body> of the document. For this purpose, we will make use of the <script> HTML tag.

In the following example, we placed a JS function inside the <body> of the document that changes the background and color of the HTML elements using the ID attribute.

JS in <body>

<!DOCTYPE html>
<html>
<body>

<div id="main-para">
Click the button to change the background of this element.
<button onclick="changeColor()">Change Color</button>
</div>

<script>
function changeColor() {
	var para = document.getElementById("main-para");
	para.style.backgroundColor = "yellow";
}
</script>
</body>
</html>

Try in CodeLab

3.3. Benefits of Internal / Onpage Scripting

There are some advantages if we include the onpage or internal JavaScript in the <head> or <body> of the document. These benefits are listed below.

Advantages Internal Scripting

  1. Better Performance: Performance is better if we use onpage scripts.
  2. Easy Maintenance: It is quite easy to maintain an onpage script that is specific for that document only.
  3. Easy Management: We can manage the onpage scripts quite efficiently, which are only usable by that particular document.
  4. Quick Execution: As the scripts are present on the same page, their execution is swift.
  5. Custom Functionality: We can enhance the functionality of the HTML elements with the internal scripts without relying on external libraries or resources.
  6. Easy Debugging: Debugging or troubleshooting the onpage script on a web page is really easy.

3.4. Drawbacks of Internal / Onpage Scripting

There are certain drawbacks of using the internal or onpage JavaScript in the <head> and in the <body> of the document. We will list them separately.

a. Drawbacks of Using the JS in <head>

  1. Slow Loading: The page loads slowly if we use the JS code inside <head> as the script will load before the page content.
  2. Content Blocking: Until the JS code is loaded and executed inside the <head>, the content of the page is blocked.
  3. Script Error: As the code in the head loads before the DOM of the document, therefore, the console shows errors sometimes when the script triggers earlier.
  4. User Experience: The UX is badly impacted by slow loading time and content blocking.

b. Drawbacks of Using the JS in <body>

  1. Inefficient Loading: Sometimes, when the user has already interacted with the content, the JavaScript code in the <body> will load afterward decreasing user experience.
  2. PageSpeed: Adding the JS code inside the <body> will affect the loading of the page and certainly the performance matrix.
  3. Compatibility Issues: Some browsers may have issues executing the script correctly when placed in the body, leading to compatibility problems.

4. JavaScript External Scripting

  • In this topic, we will discuss how to include external JavaScript sheets in a web page.
  • We utilize the HTML <script> tag to include the external script.
  • Basically, we use external scripting when we want to use the JS code again and again on several pages.
  • The process is also exemplified in the HTML script tutorial.

Look at the below instance to understand how to attach an external JavaScript file.

Adding External JS

External JavaScript File: /resources/javascript-tutorial.js
function generateRandomColor() {
	var letters = "0123456789ABCDEF";
	var color = "#";
	for (var i = 0; i < 6; i++) {
		color += letters[Math.floor(Math.random() * 16)];
	}
	return color;
}
.
.
Including the External JS file

<script src="/resources/javascript-tutorial.js"></script>

Try in CodeLab

4.1. Benefits of External Scripting

There are some advantages if we use external JavaScript resources. Check the following benefits of using external script files.

  1. Improved Performance: The external script files load asynchronously and does not block the loading of other page elements, thus increasing performance.
  2. Reusability: We can include the external JavaScript file in multiple documents as per our requirement.
  3. Better Management: If we keep the JavaScript in external files, then it will be easy to manage and keep the HTML content separate.
  4. Improved Caching: Since the browsers use cache for external script files, so they cache the files once and reuse them on further loading of the pages without loading the again and again.
  5. Reduced File Size: By keeping the JS in external files, the size of the main HTML document is reduced, which increases the loading speed.
  6. Improved Accessibility: If any user has accessibility issues, he can easily disable or block the external JavaScript files.

4.2. Drawbacks of External Scripting

Linking to external JavaScript files has some disadvantages and therefore, we should keep them in mind while developing our projects. These drawbacks are listed below.

  1. Dependency on Server: We will have to depend on the server speed and availability, which contains the external JavaScript file.
  2. Longer Load Time: If the user has slow-speed internet, then external JavaScript can cause a longer loading time of the web page.
  3. Caching Issues: Since the browsers use cache for external JavaScript files, so it can cause caching issues. Because if the external script file is modified, the browser may still load the older version.
  4. Security Concerns: If the external script file is hosted on such a server, that has vulnerability issues, then it can be a security risk.
  5. Maintaining Consistency: Keeping the external script files up-to-date can be challenging as it can take more time and effort when multiple people are involved in development.
  6. Cross-Site Scripting (XSS): Serious security issues can occur if the external JavaScript has a cross-site scripting vulnerability, so always keep checking for XSS.

5. Conclusion

Finally, we will conclude this tutorial on JavaScript with this statement that there are three methods to include JS code in a document. We can use the inline method, internal or on-page scripting method, and lastly the external scripting method. These methods completely explain how to include JavaScript code in an HTML document with the help of the CodeLab editor examples.

Give Us Your Feedback
OR
If You Need Any Help!
Contact Us