Open In App

What is Internal and External JavaScript?

Last Updated : 12 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Internal and External JavaScript are the two ways of adding JavaScript code to an HTML document. External JavaScript refers to adding JavaScript code in HTML from a separate .js file using the src attribute of <script> tag while the Internal JavaScript is the JavaScript code embedded within the script tag in the same HTML document.

Internal JavaScript

Internal JavaScript refers to embedding JavaScript code directly within the HTML file using <script> tag, either inside the <head> or <body> tag. This method is useful for small scripts specific to a single page.

Syntax

<script>  
// JavaScript code here
</script>
HTML
<!DOCTYPE html>
<html>
<body>
    <script>
    
    /*Internal Javascript*/    
    console.log("Hi Geeks, Welcome to GfG");
    </script>
</body>

</html>

Output

Hi Geeks, Welcome to GfG

Advantages

  • No need for extra HTTP requests to load scripts.
  • Easy to use for small code snippets specific to a single HTML file.

Disadvantages

  • Makes the HTML file less readable by mixing code and content.
  • Difficult to maintain when the script grows large.
  • Does not allow for JavaScript code caching.

External JavaScript

External JavaScript is when the JavaScript code written in another file having an extension .js is linked to the HMTL with the src attribute of script tag.

Syntax

<script src="url_of_js_file"> </script>

Multiple script files can also be added to one page using several <script> tags.

<script src="file1.js"> </script>
<script src="file2.js"> >/script>

The use of external JavaScript is more practical when the same code is to be used in many different web pages. Using an external script is easy , just put the name of the script file(our .js file) in the src (source) attribute of <script> tag. External JavaScript file can not contain <script> tags.

HTML
<!-- Filename: index.html -->
<!DOCTYPE html>
<html>
<body>
    <h2 id="demo">Hello...</h2>
    <script src="./script.js"></script>
</body>

</html>
JavaScript
// Filename: script.js 

let h2 = document.getElementById("demo");
h2.innerText = "This text is added by External JavaScript";

Output

Advantages

  • HTML and JavaScript files become more readable and easy to maintain.
  • Page loads speed up due to Cached JavaScript files.

Disadvantages

  • Coders can easily download your code using the url of the script(.js) file.
  • An extra HTTP request is made by the browser to get this JavaScript code.


Similar Reads