当前位置: 首页 > 知识库问答 >
问题:

按需加载脚本

曹鸿风
2023-03-14

我需要帮助。我正在创建一个项目,但在使用模板时遇到问题。我为标题和菜单创建了一个组件。菜单是一个侧边栏,在打开页面时隐藏。只有在登录后,菜单才会出现。但是javascript在那之后就不起作用了。

.angular-cli.json
------------------------------------------------------------------------

    {
      "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
      "project": {
        "name": "ticket.web.api"
      },
      "apps": [
        {
          "root": "src",
          "outDir": "dist",
          "assets": ["assets", "favicon.ico"],
          "index": "index.html",
          "main": "main.ts",
          "polyfills": "polyfills.ts",
          "test": "test.ts",
          "tsconfig": "tsconfig.app.json",
          "testTsconfig": "tsconfig.spec.json",
          "prefix": "app",
          "styles": [
            "../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",
            "styles.css"
          ],
          "scripts": [
            "../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",
          "environments": {
            "dev": "environments/environment.ts",
            "prod": "environments/environment.prod.ts"
          }
        }
      ],
      "e2e": {
        "protractor": {
          "config": "./protractor.conf.js"
        }
      },
      "lint": [
        {
          "project": "src/tsconfig.app.json",
          "exclude": "**/node_modules/**"
        },
        {
          "project": "src/tsconfig.spec.json",
          "exclude": "**/node_modules/**"
        },
        {
          "project": "e2e/tsconfig.e2e.json",
          "exclude": "**/node_modules/**"
        }
      ],
      "test": {
        "karma": {
          "config": "./karma.conf.js"
        }
      },
      "defaults": {
        "styleExt": "css",
        "component": {}
      }
    }

Header Component
------------------------------------------------------------------------
    <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" alt="stack admin 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" alt="First slide">
                    <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>
Menu Component
------------------------------------------------------------------------
    **<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>
Menu Component
------------------------------------------------------------------------


    import { Component, OnInit, AfterViewInit } from '@angular/core';

    import * as $ from 'jquery';

    import { AuthService } from '../../../security/services/auth.service';
    import { User } from '../../../security/model/auth.model';
    import { Router, NavigationEnd, ActivatedRoute } from '@angular/router';
    import { THROW_IF_NOT_FOUND } from '@angular/core/src/di/injector';
    import { Observable } from 'rxjs/Observable';
    import { Subscription } from 'rxjs/Subscription';

    @Component({
      selector: 'app-header',
      templateUrl: './header.component.html',
      styleUrls: ['./header.component.css'],
    })
    export class HeaderComponent implements OnInit, AfterViewInit {
      isLoggedIn$: Observable;
      userLogged: boolean;
      url: string;
      user: User;

      constructor(private authService: AuthService, private router: Router) {
        router.events
          .filter(event => event instanceof NavigationEnd)
          .subscribe((event: NavigationEnd) => {
            this.isLoggedIn$ = this.authService.isLoggedIn;
            this.isLoggedIn$.subscribe(res => (this.userLogged = res));
            this.url = event['url'];

            const body = document.getElementsByTagName('body')[0];
            if (this.userLogged === false) {
              body.classList.remove('menu-expanded');
            } else {
              body.classList.add('menu-expanded');
            }
            this.user = JSON.parse(localStorage.getItem('currentUser'));

          });
      }

      ngOnInit() {
        console.log('Header Component - ngOnInit');
      }

      ngAfterViewInit() {
        console.log('Header Component - ngAfterViewInit');
        console.log('---------------------------------------');
         $.getScript('../../../../assets/js/core/app.min.js').done(function() {
            console.log('Header app.min.js');
          });
          $.getScript('../../../../assets/js/core/app-menu.min.js').done(
            function() {
              console.log('Header app-menu.min.js');
            }
          );
        $.getScript('../../../../assets/js/scripts/customizer.min.js').done(
          function() {
            console.log('Header customizer.min.js');
          }
        );
      }

      logout() {
        this.authService.logout();
      }
    }


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

共有2个答案

葛宪
2023-03-14

我认为最好使用服务并使用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

萧芷阳
2023-03-14

我没有正确地得到你。但从数量我理解你的问题,你应该尝试添加你的css或脚本文件在index.html

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

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;
  }
 类似资料:
  • 出于性能的考虑,我们会对模块和组件进行按需加载。 按需加载组件 通过 umi/dynamic 接口实现,比如: import dynamic from 'umi/dynamic'; const delay = (timeout) => new Promise(resolve => setTimeout(resolve, timeout)); const App = dynamic({ loa

  • 解决这个问题的唯一方法是使用并持有一个对ids列表的引用,这不是优雅的,也不是被动的。 编辑:这是我到目前为止的解决方案,但我不得不订阅直接触发事件。我不认为它优雅。

  • 问题内容: 我正在尝试使用jQuery动态加载一些脚本: 但是有时加载脚本的顺序会发生变化。前一个脚本成功加载后,如何加载每个脚本? 问题答案: 您可以通过使用回调函数作为递归函数调用在前一个完成加载后加载每个。 在您的代码中发生的是,脚本是同时被请求的,并且由于它们是异步加载的,因此它们以随机顺序返回并执行。 我尚未对此进行测试,但是如果脚本是在本地托管的,则可以尝试以纯文本格式检索它们,然后将

  • 问题内容: 是否可以丢弃已加载的Image内容并稍后再次加载?是否可以按需加载? 我可以让ImageView仅在演出时加载图像吗? 问题答案: 不,合同中没有这种功能。图像可以在后台加载,但是一旦加载,就无法卸载。 如果使用,那么您应该显式分配它,但是JavaFX没有提供让您知道实际显示时间的方式。 要实现接近所需的功能,我将其分叉,并通过包括类充分利用了已弃用的API 。

  • 本文向大家介绍什么是按需加载?相关面试题,主要包含被问及什么是按需加载?时的应答技巧和注意事项,需要的朋友参考一下 参考回答: 当用户触发了动作时才加载对应的功能。触发的动作,是要看具体的业务场景而言,包括但不限于以下几个情况:鼠标点击、输入文字、拉动滚动条,鼠标移动、窗口大小更改等。加载的文件,可以是JS、图片、CSS、HTML等。

  • 本文向大家介绍react-router实现按需加载,包括了react-router实现按需加载的使用技巧和注意事项,需要的朋友参考一下 本文使用的 React-router 版本为 2.8.1 React Router自己就有一套按需加载解决方案,将代码拆分成多个小包,在浏览过程中实现按需加载; 如过你的项目搭配了webpack打包工具,那么需要在webpack.config.js的output内