JAVASCRIPT

Dynamically Load an External JavaScript File

Learn how to programmatically inject and execute an external JavaScript file into your web page, useful for loading libraries on demand.

function loadScript(url, callback) {
  const script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = url;

  // Handle script loading and errors
  script.onload = () => {
    console.log(`Script '${url}' loaded successfully.`);
    if (callback && typeof callback === 'function') {
      callback();
    }
  };

  script.onerror = () => {
    console.error(`Error loading script '${url}'.`);
  };

  document.head.appendChild(script);
}

// Example Usage:
// Assume 'https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js' exists
// loadScript('https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js', () => {
//   console.log('Lodash loaded! _ is available:', typeof _ !== 'undefined');
//   // You can now use lodash functions here
//   // console.log(_.camelCase('hello world'));
// });

// loadScript('/path/to/my-custom-script.js');
How it works: This snippet demonstrates how to dynamically load an external JavaScript file into the current document. It creates a new <script> element, sets its src and type attributes, and then appends it to the document's <head>. This technique is useful for loading libraries, plugins, or modules only when they are needed, improving initial page load performance. It also includes onload and onerror event handlers for robust script loading management.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs