首页 文章

在组件级别加载JS脚本(不在启动时)

提问于
浏览
26

我的项目中有很多JS文件 . 我想在应用程序启动时加载特定模块或组件时加载它们 .

这该怎么做?

目前,我正在 index.html 加载它们 . 另一种方法是在 angular-cli.json 中添加它们 . 但两种方式都会在启动时加载JS文件 . 但是,我需要在特定页面或模块运行时加载它们 .

4 回答

  • 11

    我已经回答了这个问题,但有些人怎么说不能复制 .

    请检查此链接:https://stackoverflow.com/a/44276683/6606630

    在那里你可以找到如何在组件级别的运行时加载外部JavaScript .

    您必须动态创建 script element 然后将其附加到DOM中 .

    在那个 loadScript 函数中,我只有 check existence 的单个js,如果你有多个js,那么你必须对逻辑进行一些修改 .

    如果您有任何疑问,请告诉我,我会帮助您

  • 1

    只需编写一个普通的脚本加载器

    public loadScript() {
                let body = <HTMLDivElement> document.body;
                let script = document.createElement('script');
                script.innerHTML = '';
                script.src = 'url';
                script.async = true;
                script.defer = true;
                body.appendChild(script);
        }
    

    然后在任何你想要的地方调用它:

    export class MyComponent{
    
        ngOnInit(){
            this.loadScript();
    
        }
    
    }
    

    但是如果这些文件是Typescript文件,你可以通过多种方式延迟加载它们:

    1-使用默认模块级别延迟加载

    2-使用webpack的 require

    3-使用SystemJs模块加载器

  • 13

    您可以使用RouterModule的延迟加载功能实现此目的 .

    配置您的app.module.ts,如下所示 . loadChildren -property必须指向模块的目标,并且在散列之后必须是模块的名称 .

    const routes: Routes = [
        {
            path: 'landing-page',
            loadChildren: './landing-page/landing-page.module#LandingPageModule'
        },
        {
            path: 'another-page',
            loadChildren: './another-page/another-page.module#AnotherPageModule'
        }
    ];
    
    @NgModule({
      declarations: [
        AppComponent
      ],
      imports: [
        RouterModule.forRoot(routes),
        ...
      ],
      providers: [ ... ],
      bootstrap: [AppComponent]
    })
    export class AppModule { }
    

    如果尚未完成,请将路由器插座放在html中:

    <router-outlet></router-outlet>
    

    然后配置您的页面模块,如下所示:

    const routes: Routes = [
      { path: '', component: LandingPageComponent },
      ...
    ];
    
    @NgModule({
      imports: [
        RouterModule.forChild(routes),
        ...
      ],
      declarations: [ ... ],
      providers: [ ... ]
    })
    export class LandingPageModule { }
    

    这会为每个模块生成一个块 . 在我的项目中,它看起来像这样:
    enter image description here

    当我打开我的网站时,我只会加载当前页面的所需块:

    enter image description here

  • 4

    找到.angular-cli.json文件并找到一个脚本数组然后添加你的js脚本;像这样:

    <root-directory> > .angular-cli.json > 
    "scripts": [
      "../node_modules/tinymce/tinymce.js",
      "../node_modules/tinymce/themes/modern/theme.js",
    ]
    

    或者您可以使用延迟加载...

相关问题