我在我的项目中使用了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'
});
答案 0 :(得分:1)
据我所知,问题在于行 document.body.appendChild(s);
。您正在尝试将某些内容附加到未知元素.U应该首先引用您尝试将脚本附加到的元素。由于只需添加脚本,请尝试以下代码
var win = $(window);
// Each time the user scrolls
win.scroll(function() {
// End of the document reached?
if ($(document).height() - win.height() == win.scrollTop()) {
$('#loading').show();
getEvents(10 * 2);
}
});
希望这会有所帮助
<强>更新强>
由于您使用的是角度4,因此可以使用Renderer2来解决您的目的here