问题描述
在angular 2中,可以根据组件加载CSS样式.但是,没有相应的方式来加载脚本文件.我目前正在单页应用程序的基础页上加载所有脚本,但这会导致优化问题.
In angular 2 one can load CSS styles depending on the component. However, there is no corresponding way to load script files. I am currently loading all scripts on the base page of my single page applications but that results in optimization issues.
为Angular 2/4组件加载脚本的建议方式是什么.
What is the advised way of loading scripts for an Angular 2/4 component.
推荐答案
您可以在任何组件中动态加载脚本.
Well you can load script dynamically in any component.
这是解决方法:
-
创建一个包含js文件的服务.
Create a service in which you'll have js file.
// script.store.ts
interface Scripts {
name: string;
src: string;
}
export const ScriptStore: Scripts[] = [
{ name: 'moment', src: 'https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js' },
{ name: 'datatables', src: 'https://cdn.datatables.net/v/dt/dt-1.10.12/datatables.min.js' }
];
现在创建一个将加载&返回脚本的状态.
Now create a service that will load & return the status of the script.
// script.service.ts
import { Injectable } from '@angular/core';
import { ScriptStore } from './script.store';
declare var document: any;
declare var jQuery: any;
@Injectable()
export class Script {
public scripts: any = {};
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);
}
});
}
constructor() {
ScriptStore.forEach((script: any) => {
this.scripts[script.name]={
loaded: false,
src: script.src
};
});
}
}
现在,您只需要导入&致电服务.
Now you just need to import & call the service.
// import
import {Script} from './script.service'; // specify the path where you have created the service
// Now call service
ngAfterViewInit() {
this._script.load('datatables')
.then((data:any )=>{
console.log(data,'script loaded')
})
.catch((error)=>{
});
}
它将动态添加'datatables'脚本.
It will dynamically add the script of 'datatables'.
这仅能满足您的目的,而且只会在必要时加载.
This only serves your purpose but also it will load only where it is necessary.
这篇关于Angular 2/4动态加载脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!