我想在HEAD标记中添加我的Google Analytics(分析)JS。所以我可以尝试使用angular.json
进行配置"scripts": [
"src/assets/js/jquery-3.4.1.min.js",
"src/assets/js/general.js",
{ "input": "src/assets/js/google-analytics.js", "lazy": false }
]
,但不是在head标签中添加,而是将所有js添加在body标签的末尾。
另一个选择是,将直接添加到index.html中。但我需要根据环境添加内容。
如果通过 angular.json
直接在HEAD标签中添加JS,请分享答案 0 :(得分:-1)
尝试将您的JavaScript文件添加到主应用程序的index.html文件内的head标签顶部。
您将在project-name / src / index.html
中找到它答案 1 :(得分:-1)
要从资产外部加载js文件
创建服务文件,将文件添加到资产并在数组中写入路径。
import { Injectable } from "@angular/core";
import { Injectable } from "@angular/core";
declare var document: any;
@Injectable({
providedIn:'root'
})
export class ScriptService {
private scripts: any = {};
constructor() {
ScriptConstant.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);
}
loadAll() {
var promises: any[] = [];
ScriptConstant.forEach(script => {
// promises.push(delay(1000));
promises.push(this.loadScript(script.name));
});
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("body")[0].appendChild(script);
}
});
}
}
interface Scripts {
name: string;
src: string;
}
export const ScriptConstant: Scripts[] = [
{ name: "multislider", src: "assets/js/multislider.js" },
];
在需要的地方注入此ScriptService并像这样加载js库
this.script.load('multislider').then(data => {
console.log('script loaded ', data);
}).catch(error => console.log(error));