🚀 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:

📂 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

⚡ 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.