在angular-cli中,“懒惰"如何进行?属性工作来加载全局库? [英] In angular-cli, how does the "lazy" attribute work to load global libraries?

查看:69
本文介绍了在angular-cli中,“懒惰"如何进行?属性工作来加载全局库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过将它们添加到.angular-cli文件的 scripts 属性中,可以将全局脚本加载到您的应用中.此示例来自文档:

By adding them to the scripts property of .angular-cli file, one can load global scripts into your app. This example comes from the documentation:

"scripts": [
  "global-script.js",
  { "input": "lazy-script.js", "lazy": true },
  { "input": "pre-rename-script.js", "output": "renamed-script" },
]

但是,我对懒惰"属性有些困惑.在构建应用程序时,待延迟加载的脚本不再打包在scripts.bundle.js文件中.

I am however a bit confused by the "lazy" attribute. When building your app, the to-be-lazy-loaded script is no longer packaged in the scripts.bundle.js file.

但是毕竟如何加载该库?必要时我该怎么做才能加载文件?

But how will the library then be loaded after all? What do I have to do to load the file when necessary?

推荐答案

如果在.angular-cli.json中配置懒惰"属性以加载全局库,则需要在需要时懒惰加载"脚本.这是设置步骤.

If you configure the "lazy" attribute in the .angular-cli.json to load global libraries, you need to "lazy load" the script when needed. Here is the steps to setup.

1.在apps[0].scripts阵列中配置.angular-cli.json.

"scripts": [
    { "input": "../node_modules/jquery/dist/jquery.js", "output": "jquery", "lazy": true }
],

您将在构建输出中获得一个jquery.bundle.js文件.

2.通过在DOM(<head>)中延迟添加<script>标记来加载生成的脚本.

2.Load the generated script by appending <script> tag in the DOM (<head>) lazily.

const script = document.createElement('script');
script.src = 'jquery.bundle.js';
script.type = 'text/javascript';
script.async = true;
script.charset = 'utf-8';
document.getElementsByTagName('head')[0].appendChild(script);

这篇关于在angular-cli中,“懒惰"如何进行?属性工作来加载全局库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆