任务是在 AngularJS 中在运行时从系统中动态存储的 CDN 或 JS 文件加载 JS 代码,即应该动态加载 JavaScript 代码。例如,按下按钮或发生某些事件。
每当我们想要加载脚本文件时,我们都必须使用document.createElement创建一个“脚本”类型的元素。然后我们将其 src 属性指定为 CDN 或本地 js 文件的脚本位置。完成后,我们必须将标记附加到 DOM 中已经存在的 HTML 元素。例如,头部元素。
句法:
const node = document.createElement('script');
node.src = 'SCRIPT_FILE_OR_URL_HERE'
node.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(node);
示例 1:在此示例中,我们在组件加载时从文件系统动态load.js
app.component.html
GeeksForGeeks
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Load script GFG';
constructor() {
this.loadScripts();
}
// Method to dynamically load JavaScript
loadScripts() {
// This array contains all the files/CDNs
const dynamicScripts = [
'assets/load.js'
];
for (let i = 0; i < dynamicScripts.length; i++) {
const node = document.createElement('script');
node.src = dynamicScripts[i];
node.type = 'text/javascript';
node.async = false;
document.getElementsByTagName('head')[0].appendChild(node);
}
}
}
load.js
alert('load js has been loaded');
app.component.html
GeeksForGeeks
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Load script GFG';
constructor() {
}
loadScripts($event) {
const dynamicScripts = [
'assets/load.js'
];
for (let i = 0; i < dynamicScripts.length; i++) {
const node = document.createElement('script');
node.src = dynamicScripts[i];
node.type = 'text/javascript';
node.async = false;
document.getElementsByTagName('head')[0].appendChild(node);
}
}
}
load.js
alert('load js has been loaded');
输出:一旦 app.component 加载,脚本也会加载并显示警报窗口。
示例 2:在本示例中,我们将在单击按钮时load.js
应用程序组件.html
GeeksForGeeks
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Load script GFG';
constructor() {
}
loadScripts($event) {
const dynamicScripts = [
'assets/load.js'
];
for (let i = 0; i < dynamicScripts.length; i++) {
const node = document.createElement('script');
node.src = dynamicScripts[i];
node.type = 'text/javascript';
node.async = false;
document.getElementsByTagName('head')[0].appendChild(node);
}
}
}
加载.js
alert('load js has been loaded');
输出:当按钮被按下时,JS 文件被加载。