[转]angular2: including thirdparty js scripts in component
Script tags in component templates are removed. A workaround is to create the script tag dynamically in ngAfterViewInit()
See also https://github.com/angular/angular/issues/4903
import { DOCUMENT } from '@angular/common';
...
constructor(private @Inject(DOCUMENT) document,
private elementRef:ElementRef) {};
ngAfterViewInit() {
var s = this.document.createElement("script");
s.type = "text/javascript";
s.src = "http://somedomain.com/somescript";
this.elementRef.nativeElement.appendChild(s);
}
See also https://stackoverflow.com/a/9413803/217408
Adding script tags in Angular component template
Maybe a little late to the party here, but since the above answers do not work well with Angular SSR (e.g. document is not defined server-side or document.createElement is not a function), I decided to write a version that works for Angular 4+, in both server and browser context:
Component Implementation
import { Renderer2, OnInit, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/platform-browser';
class MyComponent implements OnInit {
constructor(private _renderer2: Renderer2, @Inject(DOCUMENT) private _document) {
}
public ngOnInit() {
let s = this._renderer2.createElement('script');
s.type = `application/ld+json`;
s.text = `
{
"@context": "https://schema.org"
/* your schema.org microdata goes here */
}
`;
this._renderer2.appendChild(this._document.body, s);
}
}
Service Implementation
NOTE: Services cannot use Renderer2 directly. In fact, rendering element is supposed to be done by a Component. However, you might find yourself in situation where you want to automate the creation of JSON-LD script tags on a page. A situation could be to invoke such function on route navigation change events. Hence I decided to add a version that works in a Service context.
import { Renderer2, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/platform-browser';
class MyService {
constructor(@Inject(DOCUMENT) private _document) {
}
/**
* Set JSON-LD Microdata on the Document Body.
*
* @param renderer2 The Angular Renderer
* @param data The data for the JSON-LD script
* @returns void
*/
public setJsonLd(renderer2: Renderer2, data: any): void {
let s = renderer2.createElement('script');
s.type = `application/ld+json`;
s.text = `${JSON.stringify(data)}`;
renderer2.appendChild(this._document.body, s);
}
}
The following works with Angular 5.2.7:
The required imports are:
import { Inject, AfterViewInit, ElementRef } from '@angular/core';
import { DOCUMENT } from '@angular/common';
Implement AfterViewInit:
export class HeroesComponent implements AfterViewInit {
If your component is implementing more that one interfaces, separate them by comma; for example:
export class HeroesComponent implements OnInit, AfterViewInit {
Pass the below arguments to constructor:
constructor(@Inject(DOCUMENT) private document, private elementRef: ElementRef) { }
Add ngAfterViewInit method of view life-cycle:
ngAfterViewInit() {
const s = this.document.createElement('script');
s.type = 'text/javascript';
s.src = '//external.script.com/script.js';
const __this = this; //to store the current instance to call
//afterScriptAdded function on onload event of
//script.
s.onload = function () { __this.afterScriptAdded(); };
this.elementRef.nativeElement.appendChild(s);
}
Add afterScriptAdded member function.
This function will be called after the external script is loaded successfully. So the properties or functions you want to use from external js will be accessed in the body of this function.
afterScriptAdded() {
const params= {
width: '350px',
height: '420px',
};
if (typeof (window['functionFromExternalScript']) === 'function') {
window['functionFromExternalScript'](params);
}
}
Actually There is no Angular2 way of adding a script tag to a template. but you can do some trickfirst of all you will import AfterViewInit and ElementRef from angular2 like this :
import {Component,AfterViewInit,ElementRef} from 'Angular2/core';
then you will you will implement them in your class like that :
export class example1 implements AfterViewInit{}
and here is a very simple javascript dom trick you gonna do
export class example1 implements AfterViewInit{
ngAfterViewInit()
{
var s=document.createElement("script");
s.type="text/javascript";
s.innerHTML="console.log('done');"; //inline script
s.src="path/test.js"; //external script
}
}
I encountered the same issue, but additionally I had to load in a number of scripts, some of which could loaded in parallel, and others in series. This solution will work if you are using TypeScript 2.1 or greater, which has native support for async/await and transpiles to ES3/ES5:
async ngAfterViewInit() {
await this.loadScript("http://sub.domain.tld/first-script.js")
await this.loadScript("http://sub.domain.tld/second-script.js")
}
private loadScript(scriptUrl: string) {
return new Promise((resolve, reject) => {
const scriptElement = document.createElement('script')
scriptElement.src = scriptUrl
scriptElement.onload = resolve
document.body.appendChild(scriptElement)
})
}
For any scripts that can be loaded in parallel, you can take advantage of Promise.all:
async ngAfterViewInit() {
await Promise.all([
this.loadScript("http://sub.domain.tld/first-parallel.js"),
this.loadScript("http://sub.domain.tld/second-parallel.js")
])
await this.loadScript("http://sub.domain.tld/after-parallel.js")
}
Note: For promise rejection, you can try working with scriptElement.onerror = reject in the loadScript() function, however, I encountered some quirky behavior in this situation. If you want script to keep loading no matter what, you may want to experiment with resolving promises when onerror is called.
[转]angular2: including thirdparty js scripts in component的更多相关文章
- 使用纯粹的JS构建 Web Component
原文链接:https://ayushgp.github.io/htm...译者:阿里云 - 也树 Web Component 出现有一阵子了. Google 费了很大力气去推动它更广泛的应用,但是除 ...
- vue.js组件(component)
简介: 组件(Component)是 Vue.js 最强大的功能之一. 组件可以扩展 HTML 元素,封装可重用的代码. 组件系统让我们可以用独立可复用的小组件来构建大型应用,几乎任意类型的应用的界面 ...
- [转] angular2+highcharts+chart.js
这里是在ionic2下使用highchairs和chart.js的简单示例chartjs部分参考http://www.jianshu.com/p/bc18132da812 1.安装hightchart ...
- React.js Tutorial: React Component Lifecycle
Introduction about React component lifecycle. 1 Lifecycle A React component in browser can be any of ...
- loadrunner12.5-vugen回放脚本提示:URL=“http://www.testclass.net/js/scripts.js”的常规连接当前无套接字 (16 不足) 可用,是什么意思呢?怎么理解呢?
会发生这个报错,是因为每个浏览器都有一个限制,检查哪个浏览器客户正在模拟, 通常只允许16个并发连接. 如果超过此超过接数,将显示该消息,通知您没有可用的连接. 而max connection的默认值 ...
- [Node.js] Configuring npm package.json scripts
With a node package manager's (npm) package.json script property, you can preconfigure common tasks ...
- salesforce lightning零基础学习(八) Aura Js 浅谈一: Component篇
我们在开发lightning的时候,常常会在controller.js中写 component.get('v.label'), component.set('v.label','xxValue'); ...
- 如何在ASP.NET 5上搭建基于TypeScript的Angular2项目
一.前言 就在上月,公司的一个同事建议当前的前端全面改用AngularJs进行开发,而我们采用的就是ASP.NET 5项目,原本我的计划是采用TypeScript直接进行Angular2开发.所以借用 ...
- Karma 5:集成 Karma 和 Angular2
集成 Karma 和 Angular2 我们需要做很多工作,由于需要使用 TypeScript 进行开发,首先需要正确配置 Typescript ,然后正确配置对 Angular2 的引用.还要创建 ...
随机推荐
- UltraISO制作CentOS 7.6 U盘引导安装盘
一.制作准备: 1.UltraISO下载安装 2.CentOS镜像文件下载(阿里镜像下载) 二.制作引导盘: 1.电脑插入U盘 2.UltraISO加载镜像文件: 文件->打开->选择对应 ...
- linux 值安装yum包
1. 创建文件,挂载 rhel7-repo-iso [root@rhel7 ~]# mkdir /media/rhel7-repo-iso [root@rhel7 ~]# mount /dev/cd ...
- spring-data-redis和jedis版本对应收集总结
基于spring主版本为4.3.13.RELEASE的项目,测试以下对应版本可用. spring-data-redis版本 jedis版本 备注 1.5.2.RELEASE 2.7.3 1.6.0 ...
- [转] Firewall and network filtering in libvirt
Firewall and network filtering in libvirt There are three pieces of libvirt functionality which do n ...
- 谈谈一些有趣的CSS题目(十六)-- 奇妙的 background-clip: text
开本系列,谈谈一些有趣的 CSS 题目,题目类型天马行空,想到什么说什么,不仅为了拓宽一下解决问题的思路,更涉及一些容易忽视的 CSS 细节. 解题不考虑兼容性,题目天马行空,想到什么说什么,如果解题 ...
- [ARCH] 1、virtualbox中安装archlinux+i3桌面,并做简单美化
星期六, 28. 七月 2018 02:42上午 - beautifulzzzz 1.安装ArchLinux系统 安装Arch主要看其wiki,比较详细- 中文的我主要参考:一步步教你如何安装 Arc ...
- CSS中的px与物理像素、逻辑像素、1px边框问题
一直不太清楚CSS中的1px与逻辑像素.物理像素是个什么关系(作为一名前端感觉很惭愧 -_-!),今天终于花时间彻底弄清楚了,其实弄清楚之后就觉得事情很简单,但也只有在弄清楚之后,才会觉得简单(语出& ...
- ZJOI2019一试游记
ZJOI2019一试游记 Day -2 早上颓刀剑,中午赶动车,写一会儿作业,下午赶车到酒店,发现跟杭二的巨佬一个酒店qwq 本来想测试一下我在人群中大叫一声ljc1301 AK ZJOI2019会有 ...
- 【渗透攻防WEB篇】SQL注入攻击初级
前言不管用什么语言编写的Web应用,它们都用一个共同点,具有交互性并且多数是数据库驱动.在网络中,数据库驱动的Web应用随处可见,由此而存在的SQL注入是影响企业运营且最具破坏性的漏洞之一,这里我想问 ...
- Kali学习笔记14:SMB扫描、SMTP扫描
SMB(Server Message Block)协议,服务消息块协议. 最开始是用于微软的一种消息传输协议,因为颇受欢迎,现在已经成为跨平台的一种消息传输协议. 同时也是微软历史上出现安全问题最多的 ...