Angular Lazy Load External JS files with Angular Universal

回眸只為那壹抹淺笑 提交于 2021-02-20 04:25:14

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!