Angular cli按需加载脚本

Posted

技术标签:

【中文标题】Angular cli按需加载脚本【英文标题】:Angular cli load script on demand 【发布时间】:2018-09-13 03:34:20 【问题描述】:

我需要帮助。 我正在创建一个项目,但无法让我的模板正常工作。 我为 Header 创建了一个组件,为菜单创建了一个组件。菜单是一个侧边栏,在您打开页面时隐藏。只有登录后才会出现菜单。但是 javascript 在那之后就不起作用了。

.angular-cli.json -------------------------------------------------- ---------------------- "$schema": "./node_modules/@angular/cli/lib/config/schema.json", “项目”: “名称”:“ticket.web.api” , “应用”: [ “根”:“src”, "outDir": "dist", “资产”:[“资产”,“favicon.ico”], “索引”:“索引.html”, “main”:“main.ts”, “polyfills”:“polyfills.ts”, “测试”:“测试.ts”, "tsconfig": "tsconfig.app.json", "testTsconfig": "tsconfig.spec.json", “前缀”:“应用程序”, “风格”:[ “../node_modules/bootstrap/dist/css/bootstrap.min.css”, "./assets/fonts/feather/style.min.css", "../node_modules/font-awesome/css/font-awesome.min.css", "./assets/fonts/flag-icon-css/css/flag-icon.min.css", "./assets/vendors/css/extensions/pace.css", "./assets/vendors/css/ui/prism.min.css", "./assets/css/app.min.css", "./assets/css/core/menu/menu-types/vertical-menu.min.css", "./assets/css/core/colors/palette-gradient.min.css", "./assets/vendors/css/forms/icheck/icheck.css", "./assets/vendors/css/forms/icheck/custom.css", "./assets/css/pages/login-register.min.css", “样式.css” ], “脚本”:[ "../node_modules/jquery/dist/jquery.min.js", “../node_modules/tether/dist/js/tether.js”, “../node_modules/popper.js/dist/umd/popper.min.js”, "../node_modules/bootstrap/dist/js/bootstrap.min.js", "../node_modules/perfect-scrollbar/min/perfect-scrollbar.min.js", "./assets/vendors/js/unison/js/unison.js", "../node_modules/block-ui/jquery.blockUI.js", "../node_modules/jquery-match-height/dist/jquery.matchHeight.js", "./assets/vendors/js/slide-menu/slide-menu.js", "../node_modules/screenfull/dist/screenfull.js", "../node_modules/pace-js/pace.min.js", "../node_modules/prismjs/prism.js", "./assets/vendors/js/forms/icheck/icheck.min.js", "./assets/vendors/js/forms/validation/jqBootstrapValidation.js", "./assets/js/scripts/forms/form-login-register.min.js", **"./assets/js/core/app-menu.min.js", "./assets/js/core/app.min.js", “./assets/js/scripts/customizer.min.js”** ], "environmentSource": "environments/environment.ts", “环境”: “开发”:“环境/环境.ts”, “产品”:“环境/environment.prod.ts” ], “e2e”: “量角器”: “配置”:“./protractor.conf.js” , “棉绒”:[ “项目”:“src/tsconfig.app.json”, “排除”:“**/node_modules/**” , “项目”:“src/tsconfig.spec.json”, “排除”:“**/node_modules/**” , “项目”:“e2e/tsconfig.e2e.json”, “排除”:“**/node_modules/**” ], “测试”: “业力”: “配置”:“./karma.conf.js” , “默认值”: "styleExt": "css", “零件”: 标题组件 -------------------------------------------------- ----------------------
    <nav class="header-navbar navbar-expand-md navbar navbar-with-menu fixed-top navbar-light navbar-shadow" ***ngIf="url != '/sign-in'"** >
           <div class="navbar-wrapper">
    <div class="navbar-header">
      <ul class="nav navbar-nav flex-row">
        <li class="nav-item mobile-menu d-md-none mr-auto">
          **<a class="nav-link nav-menu-main menu-toggle hidden-xs" href="#">**
            <i class="ft-menu font-large-1"></i>
          </a>
        </li>
        <li class="nav-item">
          <a class="navbar-brand" [routerLink]="['/']">
            <img class="brand-logo"  src="assets/images/logo/stack-logo.png">
            <h2 class="brand-text">Stack</h2>
          </a>
        </li>
        <li class="nav-item d-md-none">
          <a class="nav-link open-navbar-container" data-toggle="collapse" data-target="#navbar-mobile">
            <i class="fa fa-ellipsis-v"></i>
          </a>
        </li>
      </ul>
    </div>
    <div class="navbar-container content">
      <div class="collapse navbar-collapse" id="navbar-mobile">
        <ul class="nav navbar-nav mr-auto float-left">
          <li class="nav-item d-none d-md-block" *ngIf="userLogged">
            <a class="nav-link nav-menu-main menu-toggle hidden-xs" href="#">
              <i class="ft-menu"></i>
            </a>
          </li>
          <li class="dropdown nav-item mega-dropdown">
            <a class="dropdown-toggle nav-link" href="#" data-toggle="dropdown">Menu</a>
            <ul class="mega-dropdown-menu dropdown-menu row">
              <li class="col-md-2">
                <h6 class="dropdown-menu-header text-uppercase mb-1">
                  <i class="fa fa-newspaper-o"></i> News</h6>
                <div id="mega-menu-carousel-example">
                  <div>
                    <img class="rounded img-fluid mb-1" src="assets/images/slider/slider-2.png" >
                    <a class="news-title mb-0" href="#">Poster Frame PSD</a>
                    <p class="news-content">
                      <span class="font-small-2">January 26, 2016</span>
                    </p>
                  </div>
                </div>
              </li>
              <li class="col-md-3">
                <h6 class="dropdown-menu-header text-uppercase">
                  <i class="fa fa-random"></i> Drill down menu</h6>
                <ul class="drilldown-menu">
                  <li class="menu-list">
                    <ul>
                      <li>
                        <a class="dropdown-item" href="layout-2-columns.html">
                          <i class="ft-file"></i> Page layouts & Templates</a>
                      </li>
                      <li>
                        <a href="#">
                          <i class="ft-align-left"></i> Multi level menu</a>
                        <ul>
                          <li>
                            <a class="dropdown-item" href="#">
                              <i class="fa fa-bookmark-o"></i> Second level</a>
                          </li>
                          <li>
                            <a href="#">
                              <i class="fa fa-lemon-o"></i> Second level menu</a>
                            <ul>
                              <li>
                                <a class="dropdown-item" href="#">
                                  <i class="fa fa-heart-o"></i> Third level</a>
                              </li>
                              <li>
                                <a class="dropdown-item" href="#">
                                  <i class="fa fa-file-o"></i> Third level</a>
                              </li>
                              <li>
                                <a class="dropdown-item" href="#">
                                  <i class="fa fa-trash-o"></i> Third level</a>
                              </li>
                              <li>
                                <a class="dropdown-item" href="#">
                                  <i class="fa fa-clock-o"></i> Third level</a>
                              </li>
                            </ul>
                          </li>
                          <li>
                            <a class="dropdown-item" href="#">
                              <i class="fa fa-hdd-o"></i> Second level, third link</a>
                          </li>
                          <li>
                            <a class="dropdown-item" href="#">
                              <i class="fa fa-floppy-o"></i> Second level, fourth link</a>
                          </li>
                        </ul>
                      </li>
                      <li>
                        <a class="dropdown-item" href="color-palette-primary.html">
                          <i class="ft-camera"></i> Color pallet system</a>
                      </li>
                      <li>
                        <a class="dropdown-item" href="sk-2-columns.html">
                          <i class="ft-edit"></i> Page starter kit</a>
                      </li>
                      <li>
                        <a class="dropdown-item" href="changelog.html">
                          <i class="ft-minimize-2"></i> Change log</a>
                      </li>
                      <li>
                        <a class="dropdown-item" href="#">
                          <i class="fa fa-life-ring"></i> Customer support center</a>
                      </li>
                    </ul>
                  </li>
                </ul>
              </li>
              <li class="col-md-3">
                <h6 class="dropdown-menu-header text-uppercase">
                  <i class="fa fa-list-ul"></i> Accordion</h6>
                <div id="accordionWrap" role="tablist" aria-multiselectable="true">
                  <div class="card border-0 box-shadow-0 collapse-icon accordion-icon-rotate">
                    <div class="card-header p-0 pb-2 border-0" id="headingOne" role="tab">
                      <a data-toggle="collapse" data-parent="#accordionWrap" href="#accordionOne" aria-expanded="true" aria-controls="accordionOne">Accordion Item #1</a>
                    </div>
                    <div class="card-collapse collapse show" id="accordionOne" role="tabpanel" aria-labelledby="headingOne" aria-expanded="true">
                      <div class="card-content">
                        <p class="accordion-text text-small-3">Caramels dessert chocolate cake pastry jujubes bonbon. Jelly wafer jelly beans. Caramels chocolate
                          cake liquorice cake wafer jelly beans croissant apple pie.</p>
                      </div>
                    </div>
                    <div class="card-header p-0 pb-2 border-0" id="headingTwo" role="tab">
                      <a class="collapsed" data-toggle="collapse" data-parent="#accordionWrap" href="#accordionTwo" aria-expanded="false"
                        aria-controls="accordionTwo">Accordion Item #2</a>
                    </div>
                    <div class="card-collapse collapse" id="accordionTwo" role="tabpanel" aria-labelledby="headingTwo" aria-expanded="false">
                      <div class="card-content">
                        <p class="accordion-text">Sugar plum bear claw oat cake chocolate jelly tiramisu dessert pie. Tiramisu macaroon muffin jelly
                          marshmallow cake. Pastry oat cake chupa chups.</p>
                      </div>
                    </div>
                    <div class="card-header p-0 pb-2 border-0" id="headingThree" role="tab">
                      <a class="collapsed" data-toggle="collapse" data-parent="#accordionWrap" href="#accordionThree" aria-expanded="false"
                        aria-controls="accordionThree">Accordion Item #3</a>
                    </div>
                    <div class="card-collapse collapse" id="accordionThree" role="tabpanel" aria-labelledby="headingThree" aria-expanded="false">
                      <div class="card-content">
                        <p class="accordion-text">Candy cupcake sugar plum oat cake wafer marzipan jujubes lollipop macaroon. Cake dragée jujubes donut
                          chocolate bar chocolate cake cupcake chocolate topping.</p>
                      </div>
                    </div>
                  </div>
                </div>
              </li>
              <li class="col-md-4">
                <h6 class="dropdown-menu-header text-uppercase mb-1">
                  <i class="fa fa-envelope-o"></i> Contact Us</h6>
                <form ngControl="ControlName" class="form form-horizontal">
                  <div class="form-body">
                    <div class="form-group row">
                      <label class="col-sm-3 col-form-label" for="inputName1">Name</label>
                      <div class="col-sm-9">
                        <div class="position-relative has-icon-left">
                          <input class="form-control" type="text" id="inputName1" placeholder="John Doe">
                          <div class="form-control-position pl-1">
                            <i class="fa fa-user-o"></i>
                          </div>
                        </div>
                      </div>
                    </div>
                    <div class="form-group row">
                      <label class="col-sm-3 col-form-label" for="inputEmail1">Email</label>
                      <div class="col-sm-9">
                        <div class="position-relative has-icon-left">
                          <input class="form-control" type="email" id="inputEmail1" placeholder="john@example.com">
                          <div class="form-control-position pl-1">
                            <i class="fa fa-envelope-o"></i>
                          </div>
                        </div>
                      </div>
                    </div>
                    <div class="form-group row">
                      <label class="col-sm-3 col-form-label" for="inputMessage1">Message</label>
                      <div class="col-sm-9">
                        <div class="position-relative has-icon-left">
                          <textarea class="form-control" id="inputMessage1" rows="2" placeholder="Simple Textarea"></textarea>
                          <div class="form-control-position pl-1">
                            <i class="fa fa-commenting-o"></i>
                          </div>
                        </div>
                      </div>
                    </div>
                    <div class="row">
                      <div class="col-sm-12 mb-1">
                        <button class="btn btn-primary float-right" type="button">
                          <i class="fa fa-paper-plane-o"></i> Send</button>
                      </div>
                    </div>
                  </div>
                </form>
              </li>
            </ul>
          </li>          
          **<li class="nav-item nav-search">
            <a class="nav-link nav-link-search" href="#">
              <i class="ficon ft-search"></i>
            </a>
            <div class="search-input">
              <input class="input" type="text" placeholder="Explore Stack...">
            </div>
          </li>**
        </ul>
        <ul class="nav navbar-nav float-right">
          <li class="dropdown dropdown-language nav-item">
            <a class="dropdown-toggle nav-link" id="dropdown-flag" href="#" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
              <i class="flag-icon flag-icon-gb"></i>
              <span class="selected-language">Idioma</span>
            </a>
            <div class="dropdown-menu" aria-labelledby="dropdown-flag">
              <a class="dropdown-item" href="#">
                <i class="flag-icon flag-icon-gb"></i> English</a>
              <a class="dropdown-item" href="#">
                <i class="flag-icon flag-icon-fr"></i> French</a>
              <a class="dropdown-item" href="#">
                <i class="flag-icon flag-icon-cn"></i> Chinese</a>
              <a class="dropdown-item" href="#">
                <i class="flag-icon flag-icon-de"></i> German</a>
            </div>
          </li>
          <li class="dropdown dropdown-user nav-item">
            <a *ngIf="!userLogged" class=" nav-link nav-menu-main menu-toggle hidden-xs" [routerLink]="['/sign-in']">
                <i class="fa fa-sign-in"></i> Entrar</a>
            <a *ngIf="userLogged" class="dropdown-toggle nav-link" href="#" data-toggle="dropdown">
            <span class="user-name"> user.cn </span>
            </a>
            <div class="dropdown-menu dropdown-menu-right">
              <!-- <a class="dropdown-item" href="user-profile.html">
                <i class="ft-user"></i> Edit Profile</a>
              <a class="dropdown-item" href="email-application.html">
                <i class="ft-mail"></i> My Inbox</a>
              <a class="dropdown-item" href="user-cards.html">
                <i class="ft-check-square"></i> Task</a>
              <a class="dropdown-item" href="chat-application.html">
                <i class="ft-message-square"></i> Chats</a>
              <div class="dropdown-divider"></div> -->
              <a class="dropdown-item" (click)="logout()">
                <i class="ft-power"></i> Sair</a>
            </div>
          </li>
        </ul>
      </div>
    </div>
  </div>
</nav>
菜单组件 -------------------------------------------------- ----------------------
    **<div class="main-menu menu-fixed menu-light menu-accordion menu-shadow menu-bordered" data-scroll-to-active="true" *ngIf="url != '/sign-in' && userLogged">**
      <div class="main-menu-content">
        <ul class="navigation navigation-main" id="main-menu-navigation" data-menu="menu-navigation">
          <li class="navigation-header">
            <span>General</span>
          <i class=" ft-minus" data-toggle="tooltip" data-placement="right" data-ori`enter code here`ginal-title="General"></i>
          </li>
          <li class="nav-item">
           <a [routerLink]="['/dashboard']">
            <i class="ft-home"></i>
            <span class="menu-title" data-i18n="">Dashboard</span>
          </a>
        </li>
      </ul>
     </div>
   </div>
菜单组件 -------------------------------------------------- ---------------------- 从'@angular/core'导入组件,OnInit,AfterViewInit; 从'jquery'导入*作为$; 从'../../../security/services/auth.service'导入AuthService; 从'../../../security/model/auth.model'导入用户; 从'@angular/router'导入路由器,导航结束,激活路由; 从'@angular/core/src/di/injector'导入 THROW_IF_NOT_FOUND ; 从 'rxjs/Observable' 导入 Observable ; 从'rxjs/订阅'导入订阅; @零件( 选择器:'应用程序头', templateUrl: './header.component.html', styleUrls: ['./header.component.css'], ) 导出类 HeaderComponent 实现 OnInit、AfterViewInit isLoggedIn$:可观察的; userLogged:布尔值; 网址:字符串; 用户:用户; 构造函数(私有 authService:AuthService,私有路由器:路由器) 路由器事件 .filter(event => event instanceof NavigationEnd) .subscribe((事件: NavigationEnd) => this.isLoggedIn$ = this.authService.isLoggedIn; this.isLoggedIn$.subscribe(res => (this.userLogged = res)); this.url = 事件['url']; const body = document.getElementsByTagName('body')[0]; 如果(this.userLogged === false) body.classList.remove('菜单扩展'); 别的 body.classList.add('菜单扩展'); this.user = JSON.parse(localStorage.getItem('currentUser')); ); ngOnInit() console.log('标头组件 - ngOnInit'); ngAfterViewInit() console.log('标头组件 - ngAfterViewInit'); console.log('----------------------------------------'); $.getScript('../../../../assets/js/core/app.min.js').done(function() console.log('标题 app.min.js'); ); $.getScript('../../../../assets/js/core/app-menu.min.js').done( 功能() console.log('标题 app-menu.min.js'); ); $.getScript('../../../../assets/js/scripts/customizer.min.js').done( 功能() console.log('Header customizer.min.js'); ); 登出() this.authService.logout();

每当我进入登录屏幕时,我都会隐藏导航栏和侧边栏,当它再次进入并显示时,脚本不再起作用。当我去看检查器时,脚本从元素中消失了。

【问题讨论】:

【参考方案1】:

我认为最好使用服务并使用 ReplaySubject 而不是每次都添加相同的脚本。要使用它,您必须使用字符串数组调用 loadExternals。

import  DOCUMENT  from '@angular/common';
import  Inject, Injectable  from '@angular/core';
import  forkJoin, Observable, ReplaySubject  from 'rxjs';

@Injectable( providedIn: 'root' )
export class ExternalScriptLoading 
  private libraries:  [url: string]: ReplaySubject<unknown>  = ;

  constructor(@Inject(DOCUMENT) private readonly document: Document) 

  public loadExternals(externals: string[]): Observable<unknown> 
    return forkJoin(externals.map((external: string) => this.inject(external)));
  

  private inject(link: string): Observable<unknown> 
    if (this.libraries[link]) 
      return this.libraries[link].asObservable();
    

    this.libraries[link] = new ReplaySubject();

    this.injectScript(link);

    return this.libraries[link].asObservable();
  

  private injectScript(url: string): void 
    const script: HTMLScriptElement = this.document.createElement('script');

    script.type = 'text/javascript';
    script.src = url;
    script.defer = true;
    script.onload = () => 
      this.libraries[url].next();
      this.libraries[url].complete();
    ;

    this.document.body.appendChild(script);
  

来源:https://netbasal.com/loading-external-libraries-on-demand-in-angular-9dad45701801

【讨论】:

【参考方案2】:

我没有正确理解您。但是从我理解您的问题的数量来看,您应该尝试在 index.html 中添加您的 css 或脚本文件

或者如果你想将一些脚本文件动态加载到某个特定的组件。你可以使用这些代码行。

ngOnInit() 
    this.loadScript('your path');
  

    loadScript(src)
    var script = document.createElement("script");
    script.type = "text/javascript";
    document.getElementsByTagName("head")[0].appendChild(script);
    script.src = src;
  

【讨论】:

以上是关于Angular cli按需加载脚本的主要内容,如果未能解决你的问题,请参考以下文章

ocLazyLoad angular 按需加载

vue-cli -- vantUI按需加载

按序加载

javascript按需加载

javascript按需加载

angularjs ocLazyLoad分步加载js文件,angularjs ocLazyLoad按需加载js