我在我的项目中使用了bodymovin脚本。即使我的一些SVG动画在浏览器中呈现,我仍然会收到这个错误
Uncaught TypeError: Cannot read property 'appendChild' of undefined
at SVGRenderer.configAnimation (bodymovin.min.js:5)
at AnimationItem.configAnimation (bodymovin.min.js:9)
at XMLHttpRequest.r.onreadystatechange (bodymovin.min.js:9)
at XMLHttpRequest.wrapFn [as __zone_symbol___onreadystatechange] (zone.js:1075)
at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:424)
at Zone.webpackJsonp.../../../../zone.js/dist/zone.js.Zone.runTask (zone.js:191)
at ZoneTask.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneTask.invokeTask [as invoke] (zone.js:498)
at invokeTask (zone.js:1370)
at XMLHttpRequest.globalZoneAwareCallback (zone.js:1388)根据this answer,我认为在页面上加载了所有内容之后,应该运行bodymovin脚本。我已经更新了代码,考虑到了新的建议
index.html
<!doctype html>
<html lang="en">
<head>...</head>
<body>...
<div class="full-app-body">
<app-root></app-root>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bodymovin/4.10.2/bodymovin.min.js"></script>
</body>
</html>app.component.ts
import { Component, ElementRef, OnInit, AfterViewInit } from '@angular/core';
import { Router, ActivatedRoute, RouterOutlet, Routes } from '@angular/router';
import { BrowserModule } from '@angular/platform-browser';
import { NgClass, CommonModule } from '@angular/common';
...
export class AppComponent implements AfterViewInit {
constructor(public router: Router, private elementRef: ElementRef) {}
...
ngAfterViewInit() {
const s = document.createElement('script');
s.type = 'text/javascript';
s.src = '/assets/js/animations.js';
// this.elementRef.nativeElement.appendChild(s);
document.body.appendChild(s);
}app.component.html
<div id='bm'></div>animations.js
var animation = bodymovin.loadAnimation({
container: document.getElementById('bm'),
renderer: 'svg',
loop: true,
autoplay: true,
path: './assets/images/ani/fatigue-data.json'
});发布于 2017-08-31 13:53:53
据我所知,this.elementRef.nativeElement.appendChild(s);.You试图在一个未知元素中添加一些内容,但问题是,您应该获得对您要首先将脚本附加到的元素的引用。因为这只是一个添加脚本的问题,所以尝试下面的代码
document.body.appendChild(s);希望这能帮上忙
更新
由于您使用的是角4,所以可以使用Renderer2来解决建议的here。
https://stackoverflow.com/questions/45980243
复制相似问题