簡介:
在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); } }); } }
用法:使用:
用法:
用法:this.script.load('filepicker', 'rangeSlider').then(data => { console.log('script loaded ', data); }).catch(error => console.log(error));
以上是如何使用服務在 Angular 中動態載入腳本?的詳細內容。更多資訊請關注PHP中文網其他相關文章!