How to use external “.js” files in an HTML file?

External JavaScript files are .js files containing JavaScript code that can be linked to HTML documents using the <script> tag with the src attribute. This approach separates JavaScript code from HTML markup, making code more organized, reusable, and maintainable.

Syntax

Following is the syntax to link an external JavaScript file to an HTML document −

<script src="path/to/filename.js"></script>

The src attribute specifies the path to the external JavaScript file. The path can be relative (within your project) or absolute (full URL to external resources).

Creating an External JavaScript File

An external JavaScript file is a plain text file with a .js extension containing only JavaScript code. It should not include <script> tags − those are only used in HTML documents.

Example − Creating script.js

Create a file named script.js with the following content −

function greetUser() {
    document.getElementById("greeting").innerHTML = "Hello from external JavaScript!";
}

function calculateSum(a, b) {
    return a + b;
}

// This code runs when the page loads
document.addEventListener('DOMContentLoaded', function() {
    console.log("External JavaScript file loaded successfully!");
});

Linking External JavaScript Files

External JavaScript files can be linked in the <head> section or before the closing </body> tag. The placement affects when the script executes.

Example − Basic External JavaScript

Following example demonstrates linking an external JavaScript file −

<!DOCTYPE html>
<html>
<head>
    <title>External JavaScript Example</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
    <h2>Using External JavaScript</h2>
    <p id="greeting">Click the button to see the greeting</p>
    <button onclick="greetUser()">Show Greeting</button>
    
    <script>
        // Simulating external JavaScript content inline for demo
        function greetUser() {
            document.getElementById("greeting").innerHTML = "Hello from external JavaScript!";
        }
    </script>
</body>
</html>

The output displays a button that, when clicked, changes the text using the external JavaScript function −

Using External JavaScript
Click the button to see the greeting  [Show Greeting]
(After clicking: "Hello from external JavaScript!")

Multiple External JavaScript Files

You can include multiple external JavaScript files by using multiple <script> tags. The files are loaded and executed in the order they appear.

Example − Multiple JavaScript Files

<!DOCTYPE html>
<html>
<head>
    <title>Multiple External JS Files</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
    <h2>Calculator Using External JavaScript</h2>
    <input type="number" id="num1" placeholder="First number" style="margin: 5px;">
    <input type="number" id="num2" placeholder="Second number" style="margin: 5px;">
    <br><br>
    <button onclick="addNumbers()">Add</button>
    <button onclick="multiplyNumbers()">Multiply</button>
    <p id="result"></p>
    
    <script>
        // Simulating math.js content
        function addNumbers() {
            var a = parseFloat(document.getElementById("num1").value) || 0;
            var b = parseFloat(document.getElementById("num2").value) || 0;
            document.getElementById("result").innerHTML = "Sum: " + (a + b);
        }
        
        // Simulating operations.js content
        function multiplyNumbers() {
            var a = parseFloat(document.getElementById("num1").value) || 0;
            var b = parseFloat(document.getElementById("num2").value) || 0;
            document.getElementById("result").innerHTML = "Product: " + (a * b);
        }
    </script>
</body>
</html>

This example would typically use two separate files: math.js and operations.js, loaded with −

<script src="math.js"></script>
<script src="operations.js"></script>

External JavaScript from CDN

You can also link JavaScript libraries from Content Delivery Networks (CDNs) using absolute URLs. This is common for popular libraries like jQuery, Bootstrap, or other frameworks.

Example − Using jQuery from CDN

<!DOCTYPE html>
<html>
<head>
    <title>jQuery from CDN</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
    <h2>jQuery Example</h2>
    <p id="jqDemo">Original text</p>
    <button id="changeText">Change Text with jQuery</button>
    <button id="hideText">Hide Text</button>
    
    <script>
        $(document).ready(function() {
            $("#changeText").click(function() {
                $("#jqDemo").text("Text changed using jQuery!");
            });
            
            $("#hideText").click(function() {
                $("#jqDemo").fadeOut();
            });
        });
    </script>
</body>
</html>

This example loads jQuery from a CDN and uses it to manipulate DOM elements with smooth animations.

Internal vs External JavaScript Internal JavaScript ? Code inside <script> tags ? Mixed with HTML ? Not reusable ? Harder to maintain ? Faster initial load ? No caching benefits External JavaScript ? Code in separate .js files ? Clean separation ? Highly reusable ? Easy to maintain ? Browser caching ? Parallel development

Best Practices for External JavaScript

Following are the recommended practices when using external JavaScript files −

  • File placement − Place <script> tags before the closing </body> tag to ensure DOM elements are loaded before JavaScript executes.

  • File naming − Use descriptive names like navigation.js, validation.js, or utils.js instead of generic names.

  • Minification − Use minified versions of libraries (e.g., jquery.min.js) for better performance in production.

  • Error handling − Always test that external files load correctly. Use browser developer tools to check for 404 errors.

Advantages of External JavaScript Files

Using external JavaScript files provides several benefits over inline JavaScript −

Advantage Description
Code Reusability Same JavaScript file can be used across multiple HTML pages
Better Organization Separates structure (HTML) from behavior (JavaScript)
Caching Browsers cache external files, reducing load times on subsequent visits
Maintainability Changes to JavaScript require editing only one file
Parallel Development HTML and JavaScript can be developed independently
Cleaner HTML HTML files remain focused on structure and content

Common File Paths

External JavaScript files can be referenced using different path types −

Relative Paths

<!-- Same folder -->
<script src="script.js"></script>

<!-- Subfolder -->
<script src="js/script.js"></script>

<!-- Parent folder -->
<script src="../script.js"></script>

Absolute Paths

<!-- From domain root -->
<script src="/js/script.js"></script>

<!-- External CDN -->
<script src="https://cdn.example.com/library.js"></script>

Conclusion

External JavaScript files provide better code organization, reusability, and maintainability compared to inline scripts. By separating JavaScript from HTML and leveraging browser caching, external files improve both development workflow and website performance. Always use descriptive filenames and place script tags appropriately for optimal results.

Updated on: 2026-03-16T20:54:42+05:30

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements