简介:
在 Angular 应用程序中,需要包含外部脚本可以出现。但是,添加 <script>直接将标签添加到index.html并依赖ES6导入语句有局限性。本文介绍了一种根据用户配置动态加载脚本的技术,允许开发者在 CDN 或本地脚本源之间进行选择。</script>
动态脚本加载:
动态加载脚本,我们可以采用以下步骤:
示例代码:
下面是脚本存储和服务的示例实现:
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); } }); } }
用法:
在您希望动态加载脚本的组件或服务,注入 ScriptService。然后,在一个方法中,像这样调用 load 方法:
this.script.load('filepicker', 'rangeSlider').then(data => { console.log('script loaded ', data); }).catch(error => console.log(error));
在此示例中,filepicker 和 rangeSlider 脚本都将动态加载。您现在可以配置 ScriptStore 以根据需要从 CDN 或本地文件夹加载脚本。
以上是如何使用服务在 Angular 中动态加载脚本?的详细内容。更多信息请关注PHP中文网其他相关文章!