我正在使用Angular 4和CLI创建一个Angular应用程序。我正在尝试将SkyScanner搜索小部件添加到我的一个组件中。
部分实施需要添加新的外部脚本:
<script src="https://widgets.skyscanner.net/widget-server/js/loader.js" async></script>
我不确定引用此文件的正确方法。如果我将脚本添加到我的index.html文件中,除非执行整页刷新,否则不会加载窗口小部件。我假设脚本在加载时尝试操作DOM,并且在脚本运行时元素不存在。
仅在加载包含Skyscanner窗口小部件的组件时加载脚本的正确方法是什么?
答案 0 :(得分:49)
尝试在组件加载上加载外部JavaScript,如下所示:
loadAPI: Promise<any>;
constructor() {
this.loadAPI = new Promise((resolve) => {
this.loadScript();
resolve(true);
});
}
public loadScript() {
var isFound = false;
var scripts = document.getElementsByTagName("script")
for (var i = 0; i < scripts.length; ++i) {
if (scripts[i].getAttribute('src') != null && scripts[i].getAttribute('src').includes("loader")) {
isFound = true;
}
}
if (!isFound) {
var dynamicScripts = ["https://widgets.skyscanner.net/widget-server/js/loader.js"];
for (var i = 0; i < dynamicScripts .length; i++) {
let node = document.createElement('script');
node.src = dynamicScripts [i];
node.type = 'text/javascript';
node.async = false;
node.charset = 'utf-8';
document.getElementsByTagName('head')[0].appendChild(node);
}
}
}
答案 1 :(得分:14)
我有同样的问题,但在我的情况下,我在html文件的末尾导入了10个库,这些库有很多方法,听众,事件等等,在我的情况下我没有'需要专门调用一个方法。
关于我所拥有的例子:
<!-- app.component.html -->
<div>
...
</div>
<script src="http://www.some-library.com/library.js">
<script src="../assets/js/my-library.js"> <!-- a route in my angular project -->
如上所述,它没有用。然后,我找到了帮助我的东西:Milad response
删除app.component.html中的脚本调用。您必须在app.component.ts文件中链接这些脚本。
在ngOnInit()中,使用方法追加库,例如:
``
<!-- app.component.ts -->
export class AppComponent implements OnInit {
title = 'app';
ngOnInit() {
this.loadScript('http://www.some-library.com/library.js');
this.loadScript('../assets/js/my-library.js');
}
}
public loadScript(url: string) {
const body = <HTMLDivElement> document.body;
const script = document.createElement('script');
script.innerHTML = '';
script.src = url;
script.async = false;
script.defer = true;
body.appendChild(script);
}
}
它对我有用。我使用Angular 6,希望它有所帮助。
答案 2 :(得分:6)
我已完成此代码段
addJsToElement(src: string): HTMLScriptElement {
const script = document.createElement('script');
script.type = 'text/javascript';
script.src = src;
this.elementRef.nativeElement.appendChild(script);
return script;
}
然后像这样称呼它
this.addJsToElement('https://widgets.skyscanner.net/widget-server/js/loader.js').onload = () => {
console.log('SkyScanner Tag loaded');
}
编辑:使用新的渲染器Api,可以像这样编写
constructor(private renderer: Renderer2){}
addJsToElement(src: string): HTMLScriptElement {
const script = document.createElement('script');
script.type = 'text/javascript';
script.src = src;
this.renderer.appendChild(document.body, script);
return script;
}
<强> StackBlitz 强>
答案 3 :(得分:5)
将loader.js
添加到您的资源文件夹,然后添加到angular-cli.json
"scripts": ["./src/assets/loader.js",]
然后将其添加到您的typings.d.ts
declare var skyscanner:any;
你可以使用它
skyscanner.load("snippets","2");
答案 4 :(得分:4)
您可以创建自己的指令来加载脚本,如下所示
import { Directive, OnInit, Input } from '@angular/core';
@Directive({
selector: '[appLoadScript]'
})
export class LoadScriptDirective implements OnInit{
@Input('script') param: any;
ngOnInit() {
let node = document.createElement('script');
node.src = this.param;
node.type = 'text/javascript';
node.async = false;
node.charset = 'utf-8';
document.getElementsByTagName('head')[0].appendChild(node);
}
}
您可以在组件模板中的任何位置使用它,如下所示
<i appLoadScript [script]="'script_file_path'"></i>
例如,要在组件中动态加载JQuery,请在组件的模板中插入以下代码
<i appLoadScript [script]="'/assets/baker/js/jquery.min.js'"></i>
答案 5 :(得分:0)
你可以做一件事
如果你有angular-cli.json
然后你可以声明脚本
像
"scripts": ["../src/assets/js/loader.js"]
然后在组件中声明skyscanner
喜欢
declare var skyscanner:any;
多数民众赞成!
希望这能帮到你
答案 6 :(得分:0)
注意:这是专门针对外部js链接的! 步骤1.建议将角度脚本添加到身体底部的index.html文件中!我尝试了所有其他方法但失败了。
<!-- File Name: index.html and its inside src dir-->
<body class="">
<app-root></app-root>
<!-- Icons -->
<script src="https://unpkg.com/feather-icons/dist/feather.min.js"></script>
</body>
接下来有两种方法可以做到这一点...... 在Anguar5中,在此代码中顶部类型的组件文件夹中使用
declare var feather:any;
然后在你的课程中调用你需要的方法。例如
//FileName: dashboard.component.ts
import { Component, OnInit } from '@angular/core';
declare var feather:any;
export class DashboardComponent implements OnInit{
ngOnInit(){
feather.replace();
}
}
这应该运行你的代码! 另一种可能适用于旧版本的方式。我没有检查过!
//FileName: dashboard.component.ts
import { Component, OnInit } from '@angular/core';
export class DashboardComponent implements OnInit{
ngOnInit(){
let node = document.createElement('script');
node.innerText='feather.replace()';
node.type = 'text/javascript';
node.async = false;
node.charset = 'utf-8';
document.getElementsByTagName('body')[0].appendChild(node);
}
}
如果您没有收到我的代码,那么也请尝试这个link。
希望这有帮助!
答案 7 :(得分:0)
来晚了,但是我更喜欢这样(服务方式)。...
import { Injectable } from '@angular/core';
import { Observable } from "rxjs";
interface Scripts {
name: string;
src: string;
}
export const ScriptStore: Scripts[] = [
{ name: 'script-a', src: 'assets/js/a.js' },
{ name: 'script-b', src: 'assets/js/b.js' },
{ name: 'script-c', src: 'assets/js/c.js' }
];
declare var document: any;
@Injectable()
export class FileInjectorService {
private scripts: any = {};
constructor() {
ScriptStore.forEach((script: any) => {
this.scripts[script.name] = {
loaded: false,
src: script.src
};
});
}
loadJS(...scripts: string[]) {
const promises: any[] = [];
scripts.forEach((script) => promises.push(this.loadJSFile(script)));
return Promise.all(promises);
}
loadJSFile(name: string) {
return new Promise((resolve, reject) => {
if (!this.scripts[name].loaded) {
let script = document.createElement('script');
script.type = 'text/javascript';
script.src = this.scripts[name].src;
if (script.readyState) {
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 {
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);
} else {
resolve({ script: name, loaded: true, status: 'Already Loaded' });
}
});
}
}
然后在我的组件中,我可以做类似的事情:
ngOnInit() {
this.fileInjectorService.loadJS('script-a', 'script-c').then(data => {
// Loaded A and C....
}).catch(error => console.log(error));
}
在Angular 6/7中测试
答案 8 :(得分:0)
可接受的答案是正确的,但无法使用,因为浏览器在下载脚本后花了更多时间来解析脚本。因此,如果正在从加载的脚本中使用任何变量,则需要在新创建的html脚本元素的onload事件上使用它。我已经改进了如下所述的可接受答案-
loadAPI: Promise<any>;
constructor() {
this.loadAPI = new Promise((resolve) => {
let node = this.loadScript();
if (node) {
node.onload = () => {
resolve(true);
};
} else {
resolve(true);
}
});
}
ngOnInit() {
this.loadAPI
.then((flag) => {
//Do something when script is loaded and parsed by browser
});
}
loadScript() {
let node = undefined;
let isFound = false;
const scripts = document.getElementsByTagName('script')
for (let i = 0; i < scripts.length; ++i) {
// Check if script is already there in html
if (scripts[i].getAttribute('src') != null && scripts[i].getAttribute('src').includes("loader")) {
isFound = true;
}
}
if (!isFound) {
const dynamicScript = 'https://widgets.skyscanner.net/widget-server/js/loader.js';
node = document.createElement('script');
node.src = dynamicScript;
node.type = 'text/javascript';
node.async = false;
node.charset = 'utf-8';
document.getElementsByTagName('head')[0].appendChild(node);
return node;
}
return node;
}
答案 9 :(得分:0)
经过大量的代码试用,这对我有用
ngOnInit() {
this.loadFormAssets().then(() => {console.log("Script Loaded");}).catch(() => {console.log("Script Problem");});
}
public loadFormAssets() {
return new Promise(resolve => {
const scriptElement = document.createElement('script');
scriptElement.src =this.urls.todojs;
scriptElement.onload = resolve;
document.body.appendChild(scriptElement);
const scriptElement1 = document.createElement('script');
scriptElement1.src =this.urls.vendorjs;
scriptElement1.onload = resolve;
document.body.appendChild(scriptElement1);
});
}
答案 10 :(得分:0)
在我的情况下,我必须加载一些相互依赖的不同文件(某种使用引导程序,然后使用jquery插件,然后使用jquery的文件),并且假定加载了它们,它们在加载时立即立即初始化在网页上同步。所有其他答案均假定您正在加载完全不相关的文件(或在加载所有内容后等待您初始化)-而在我的设置下,这将引发各种丢失的变量问题。
我的解决方案是创建一个Promise
链(而不是像@carlitoxenlaweb这样的Promise
列表-它将并行解析所有内容),以便仅在前一个文件具有完成的初始化:
private myScripts = [
'/assets/js/jquery-2.2.4.min.js',
'/assets/js/bootstrap.min.js',
'/assets/js/jquery.bootstrap.js',
'/assets/js/jquery.validate.min.js',
'/assets/js/somescript.js',
];
private loadScripts() {
let container:HTMLElement = this._el.nativeElement;
let promise = Promise.resolve();
for (let url of this.myScripts) {
promise = promise.then(_ => new Promise((resolve, reject) => {
let script = document.createElement('script');
script.innerHTML = '';
script.src = url;
script.async = true;
script.defer = false;
script.onload = () => { resolve(); }
script.onerror = (e) => { reject(e); }
container.appendChild(script);
}));
}
}
答案 11 :(得分:0)
由于源 URL 允许您调用全局函数,因此您可以使用它来设置自定义事件处理程序。
index.html
<script
type="text/javascript"
src="http://www.bing.com/api/maps/mapcontrol?callback=onBingLoaded&branch=release"
async defer
></script>
<script>
function onBingLoaded() {
const event = new CustomEvent("bingLoaded");
window.dispatchEvent(event);
}
</script>
既然我们已经将自定义事件分派到 window 对象,我们可以使用 Angular 在组件中提供的装饰器 @HostListener
来监听它。
app.component.ts
export class AppComponent {
@ViewChild('mapCanvas')
mapCanvas!: ElementRef;
private map!: Microsoft.Maps.Map;
@HostListener('window:bingLoaded', ['$event'])
defineMapCanvas() {
this.map = new Microsoft.Maps.Map(
this.mapCanvas.nativeElement,
{
credentials: [YOUR API KEY HERE],
...other options
}
);
}