"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can I Dynamically Load Scripts in Angular Using a Service?

How Can I Dynamically Load Scripts in Angular Using a Service?

Published on 2024-11-25
Browse:469

How Can I Dynamically Load Scripts in Angular Using a Service?

Dynamic Script Loading in Angular: A Solution

Introduction:

In Angular applications, the need to include external scripts can arise. However, adding

Dynamic Script Loading:

To dynamically load scripts, we can employ the following steps:

  1. Create a Script Store: Establish an array of objects called ScriptStore, which holds script paths and unique names for dynamic loading.
  2. Inject the Script Service: Implement the ScriptService as an injectable Angular service that manages script loading.
  3. Load Scripts Method: Define a load method in ScriptService to load scripts dynamically. This method takes script names as parameters and returns a promise.
  4. Load Script Implementation: Within the load method, check if the script is already loaded. If not, create a
  5. Inject and Invoke the Service: Inject ScriptService into the component or service where you need to load scripts. Call the load method to load the desired scripts.

Example Code:

Below is a sample implementation of the script store and service:

interface Scripts {
  name: string;
  src: string;
}

// Script store with sample script definitions
export const ScriptStore: Scripts[] = [
  { name: 'filepicker', src: 'https://api.filestackapi.com/filestack.js' },
  { name: 'rangeSlider', src: '../../../assets/js/ion.rangeSlider.min.js' }
];

@Injectable()
export class ScriptService {
  private scripts: any = {};

  constructor() {
    ScriptStore.forEach((script: any) => {
      this.scripts[script.name] = {
        loaded: false,
        src: script.src
      };
    });
  }

  load(...scripts: string[]) {
    var promises: any[] = [];
    scripts.forEach((script) => promises.push(this.loadScript(script)));
    return Promise.all(promises);
  }

  loadScript(name: string) {
    return new Promise((resolve, reject) => {
      // Check if script is already loaded
      if (this.scripts[name].loaded) {
        resolve({ script: name, loaded: true, status: 'Already Loaded' });
      } else {
        let script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = this.scripts[name].src;
        script.onload = () => {
          this.scripts[name].loaded = true;
          resolve({ script: name, loaded: true, status: 'Loaded' });
        };
        script.onerror = (error: any) => resolve({ script: name, loaded: false, status: 'Loaded' });
        document.getElementsByTagName('head')[0].appendChild(script);
      }
    });
  }
}

Usage:

In the component or service where you wish to load scripts dynamically, inject the ScriptService. Then, within a method, invoke the load method like this:

this.script.load('filepicker', 'rangeSlider').then(data => {
  console.log('script loaded ', data);
}).catch(error => console.log(error));

In this example, both filepicker and rangeSlider scripts will be loaded dynamically. You can now configure the ScriptStore to load scripts from either a CDN or a local folder as needed.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3