I'm trying to learn how to use external JavaScript libraries in projects generated by angular-cli. I'm writing an application that renders molecules in the browser, so I am using Kekule.js.
This library is not available over npm, so I have to import it manually so that webpack knows it exists. I followed the advice I found about external js libraries and angular-cli to declare the variables in main.ts:
import './polyfills.ts';
window['$'] = require('jquery');
window['Kekule'] = require("../libs/kekule/kekule.js");
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { enableProdMode } from '@angular/core';
import { environment } from './environments/environment';
import { AppModule } from './app/';
if (environment.production) {
enableProdMode();
}
platformBrowserDynamic().bootstrapModule(AppModule);
This does seem to initialize Kekule.js and pass it the $root
variable.
However, I'm getting an error when init()
method runs in Kekule.js. It calls another method that looks for all elements in the DOM with the script tag: $root.document.getElementsByTagName('script')
but throws this error:
Uncaught TypeError: Cannot read property 'getElementsByTagName' of undefined
at analysisEntranceScriptSrc (kekule.js:462)
at init (kekule.js:574)
at kekule.js:614
at Object.<anonymous> (kekule.js:616)
at Object.682 (main.bundle.js:910)
at __webpack_require__ (bootstrap dcc310b…:52)
at Object.469 (index.ts:2)
at __webpack_require__ (bootstrap dcc310b…:52)
at Object.467 (main.ts:15)
at __webpack_require__ (bootstrap dcc310b…:52)
I did some testing and $root.document
is indeed undefined
for me when the script tries to run. I've tried just loading the script tags in index.html, but that then threw typescript errors that variable references to Kekule were not defined in my typescript classes.
- Is this happening because angular is providing
$root
the wrong execution context? - Or is this happening because angular loads the script before the DOM is created?
- Some other problem?
Any help understanding/fixing this would be greatly appreciated!