JavaScript  

How do I load external JavaScript dynamically in Angular?

🚀 Why load JavaScript dynamically?

Sometimes, including a script in your Angular project permanently is not the best idea. Here’s why you may want to load JavaScript dynamically:

  • Optional Features: You might only need a script for a specific feature or page. Loading it everywhere wastes resources.
  • Conditional Loading: Some scripts may only be needed in certain situations, like user role-specific dashboards or admin-only tools.
  • Better Performance: By loading scripts only when needed, you reduce the initial load time of your Angular app.
  • Configurable Sources: Sometimes, the script URL comes from an API or settings, so you cannot hardcode it in advance.

📂 Different Approaches to Load JavaScript

1. Using angular.json (Static Inclusion)

If the script is always needed, you can add it in the angular.json configuration file:

"scripts": [
  "src/assets/js/external-library.js"
]

This will make the script available everywhere in your Angular app. However, this approach is static and does not support conditional loading.

2. Adding Script in index.html

Another simple way is to place the script inside the index.html file:

<script src="https://example.com/external-library.js"></script>

This ensures the script loads before your Angular application runs. The downside is that it loads on every page, whether it is needed or not.

3. Dynamic Script Loading with a Service (Recommended)

A better way is to create a reusable service that loads JavaScript dynamically when you need it.

Example:

import { Injectable } from '@angular/core';

@Injectable({ providedIn: 'root' })
export class ScriptLoaderService {
  loadScript(url: string): Promise<void> {
    return new Promise((resolve, reject) => {
      const script = document.createElement('script');
      script.src = url;
      script.async = true;
      script.onload = () => resolve();
      script.onerror = () => reject(`Script load error: ${url}`);
      document.body.appendChild(script);
    });
  }
}

Now you can use this service inside any component:

constructor(private scriptLoader: ScriptLoaderService) {}

ngOnInit() {
  this.scriptLoader.loadScript('https://example.com/external-library.js')
    .then(() => {
      console.log('Script loaded successfully');
      // Use the external library here
    })
    .catch(err => console.error(err));
}

This method gives you full control and prevents unnecessary scripts from loading globally.

4. Using Angular Renderer2 (For Security)

Angular provides Renderer2 which is a safer way to manipulate the DOM.

Example:

import { Component, Renderer2 } from '@angular/core';

@Component({
  selector: 'app-dynamic-loader',
  template: `<h2>Dynamic Script Example</h2>`
})
export class DynamicLoaderComponent {
  constructor(private renderer: Renderer2) {
    const script = this.renderer.createElement('script');
    script.src = 'https://example.com/external-library.js';
    script.onload = () => console.log('Script loaded');
    this.renderer.appendChild(document.body, script);
  }
}

This is recommended when you want to avoid directly manipulating the DOM.

🛡️ Best Practices for Loading Scripts

  • Always use trusted sources: Only load scripts from reliable providers.
  • Use HTTPS: Prevent security warnings by avoiding insecure (HTTP) scripts.
  • Lazy load when possible: Load scripts only when they are needed.
  • Prefer Angular’s Renderer2: Safer than directly accessing document.
  • Avoid unnecessary scripts: Loading too many scripts will slow down your application.

⚡ Example: Loading Google Maps API Dynamically

Let’s say you want to add Google Maps only when a user opens the “Map” component.

Example:

ngOnInit() {
  this.scriptLoader.loadScript('https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY')
    .then(() => {
      const map = new google.maps.Map(document.getElementById('map') as HTMLElement, {
        center: { lat: 28.7041, lng: 77.1025 },
        zoom: 10
      });
    });
}

This ensures Google Maps API is only downloaded when required, improving overall app performance.

📝 Summary

Loading external JavaScript dynamically in Angular helps you make your application faster, more flexible, and more secure. Instead of loading scripts everywhere, you can decide when and where to load them. The best method is to use a script loader service or Renderer2 for security. Always follow best practices to avoid security risks and improve user experience.