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