JAVASCRIPT

Dynamically Loading External JavaScript or CSS Files

Learn to programmatically load external JavaScript scripts or CSS stylesheets into your web page, enabling on-demand resource loading for better performance.

function loadResource(url, type, callback) {
  if (type === 'js') {
    const script = document.createElement('script');
    script.src = url;
    script.async = true; // For non-blocking script loading
    script.onload = () => callback && callback();
    script.onerror = () => console.error(`Failed to load script: ${url}`);
    document.head.appendChild(script);
  } else if (type === 'css') {
    const link = document.createElement('link');
    link.rel = 'stylesheet';
    link.href = url;
    link.onload = () => callback && callback();
    link.onerror = () => console.error(`Failed to load stylesheet: ${url}`);
    document.head.appendChild(link);
  } else {
    console.error('Invalid resource type. Use "js" or "css".');
  }
}

// Example Usage:
// loadResource('https://example.com/some-library.js', 'js', () => {
//   console.log('Script loaded successfully!');
// });
// loadResource('/styles/theme.css', 'css');
How it works: This function demonstrates how to dynamically load external JavaScript or CSS files into a webpage. It creates either a `<script>` or `<link>` element based on the specified `type`, sets its `src` or `href` attribute, and appends it to the document's `<head>`. Callbacks can be provided to execute code once the resource has successfully loaded or to handle potential loading errors. This technique is valuable for lazy loading resources, implementing feature-specific scripts, or dynamically changing themes without a full page reload.

Need help integrating this into your project?

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

Hire DigitalCodeLabs