问题
https://maps.googleapis.com/maps/api/js?libraries=places&key=XXX
This is inside index.html file, but i want to lazy load this script, because that module is lazy loaded and it's really not necessary for all users. I can't use trick with directly accessing the DOM and appending script el. because I want to use Angular Universal ( SSR ).
回答1:
You can access the DOM even if you are using SSR. Add this to your lazy loaded module module or one of the components of your lazy loaded module
import {DOCUMENT} from "@angular/common";
import {Renderer2} from '@angular/core';
constructor(@Inject(DOCUMENT) private document: any, private renderer: Renderer2)
{
}
constructor()
{
const scriptElt = this.renderer.createElement('script');
this.renderer.setAttribute(scriptElt, 'type', 'text/javascript');
this.renderer.setAttribute(scriptElt, 'src', 'yourJSFile.js');
this.renderer.appendChild(this.document.head, scriptElt);
}
来源:https://stackoverflow.com/questions/61204847/angular-lazy-load-external-js-files-with-angular-universal