How to load a JavaScript file Dynamically?

Loading JavaScript files dynamically allows you to add scripts to your webpage at runtime, which is useful for conditional loading, lazy loading, or modular applications.

Basic Dynamic Loading Method

The most common approach is creating a <script> element and appending it to the document head:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Dynamic JavaScript Loading</title>
    <style>
        body {
            font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
            padding: 20px;
        }
        .result {
            font-size: 20px;
            font-weight: 500;
            color: green;
            margin: 20px 0;
        }
        button {
            background: #007bff;
            color: white;
            border: none;
            padding: 10px 20px;
            cursor: pointer;
            border-radius: 4px;
        }
    </style>
</head>
<body>
    <h1>Load a JavaScript file Dynamically</h1>
    <div class="result"></div>
    <button class="loadBtn">CLICK HERE</button>
    <p>Click the above button to load external JavaScript</p>

    <script>
        let resEle = document.querySelector(".result");
        
        document.querySelector(".loadBtn").addEventListener("click", () => {
            var jsRef = document.createElement("script");
            jsRef.setAttribute("src", "sample.js");
            jsRef.onload = () => {
                console.log("Script loaded successfully");
            };
            jsRef.onerror = () => {
                resEle.innerHTML = 'Error loading JavaScript file';
                resEle.style.color = 'red';
            };
            document.getElementsByTagName("head")[0].appendChild(jsRef);
        });
    </script>
</body>
</html>

External JavaScript File (sample.js)

// This would be in your sample.js file
resEle.innerHTML = 'JavaScript has been loaded successfully!';

Using Promises for Better Control

For more robust script loading with proper error handling, you can wrap the loading process in a Promise:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Promise-based Script Loading</title>
</head>
<body>
    <div id="status"></div>
    <button onclick="loadScript()">Load Script with Promise</button>

    <script>
        function loadScriptAsync(src) {
            return new Promise((resolve, reject) => {
                const script = document.createElement('script');
                script.src = src;
                script.onload = () => resolve(script);
                script.onerror = () => reject(new Error(`Script load error for ${src}`));
                document.head.appendChild(script);
            });
        }

        async function loadScript() {
            const statusDiv = document.getElementById('status');
            try {
                statusDiv.innerHTML = 'Loading script...';
                await loadScriptAsync('sample.js');
                statusDiv.innerHTML = 'Script loaded successfully!';
                statusDiv.style.color = 'green';
            } catch (error) {
                statusDiv.innerHTML = `Failed to load: ${error.message}`;
                statusDiv.style.color = 'red';
            }
        }
    </script>
</body>
</html>

Key Features

  • onload event: Executes when the script loads successfully
  • onerror event: Handles loading failures
  • Async loading: Scripts load without blocking page rendering
  • Conditional loading: Load scripts based on user actions or conditions

Common Use Cases

  • Loading third-party libraries on demand
  • Implementing lazy loading for performance
  • Loading different scripts based on user preferences
  • Adding functionality after user interaction

Conclusion

Dynamic JavaScript loading provides flexibility for managing scripts in modern web applications. Use event handlers like onload and onerror for proper error handling and user feedback.

Updated on: 2026-03-15T23:18:59+05:30

690 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements