gpt4 book ai didi

javascript - 如何在 Angular 中动态加载外部脚本?

转载 作者:行者123 更新时间:2023-12-05 07:32:46 24 4
gpt4 key购买 nike

我有这个模块,无需添加 <script> 即可将外部库与附加逻辑一起组件化。直接标记到 index.html 中:

import 'http://external.com/path/file.js'
//import '../js/file.js'

@Component({
selector: 'my-app',
template: `
<script src="http://iknow.com/this/does/not/work/either/file.js"></script>
<div>Template</div>`
})
export class MyAppComponent {...}

我注意到 import ES6 规范是静态的,并在 TypeScript 转译期间而不是在运行时解析。

无论如何使其可配置,以便 file.js 将从 CDN 或本地文件夹加载?如何告诉 Angular 2 动态加载脚本?

最佳答案

您可以使用以下技术来在 Angular 项目中按需动态加载 JS 脚本和库。

script.store.ts 将包含本地或远程服务器上脚本的路径,以及将使用的名称动态加载脚本

 interface Scripts {
name: string;
src: string;
}
export const ScriptStore: Scripts[] = [
{name: 'filepicker', src: 'https://api.filestackapi.com/filestack.js'},
{name: 'rangeSlider', src: '../../../assets/js/ion.rangeSlider.min.js'}
];

script.service.ts 是一个可注入(inject)的服务,它将处理脚本的加载,按原样复制 script.service.ts

import {Injectable} from "@angular/core";
import {ScriptStore} from "./script.store";

declare var document: any;

@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) => {
//resolve if already loaded
if (this.scripts[name].loaded) {
resolve({script: name, loaded: true, status: 'Already Loaded'});
}
else {
//load script
let script = document.createElement('script');
script.type = 'text/javascript';
script.src = this.scripts[name].src;
if (script.readyState) { //IE
script.onreadystatechange = () => {
if (script.readyState === "loaded" || script.readyState === "complete") {
script.onreadystatechange = null;
this.scripts[name].loaded = true;
resolve({script: name, loaded: true, status: 'Loaded'});
}
};
} else { //Others
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);
}
});
}

}

在你需要的地方注入(inject)这个 ScriptService 并像这样加载 js 库

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

关于javascript - 如何在 Angular 中动态加载外部脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51054710/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com