通过将它们添加到.angular-cli文件的scripts属性,可以将全局脚本加载到您的应用程序中.这个例子来自
documentation:
"scripts": [ "global-script.js",{ "input": "lazy-script.js","lazy": true },{ "input": "pre-rename-script.js","output": "renamed-script" },]
然而,我对“懒惰”属性感到有点困惑.构建应用程序时,不再将待加载的脚本打包在scripts.bundle.js文件中.
但是毕竟如何加载图书馆呢?必要时我该怎么做才能加载文件?
解决方法
如果在.angular-cli.json中配置“lazy”属性以加载全局库,则需要在需要时“延迟加载”脚本.以下是设置步骤.
1.在apps [0] .scripts数组中配置.angular-cli.json.
"scripts": [ { "input": "../node_modules/jquery/dist/jquery.js","output": "jquery","lazy": true } ],
You’ll get an
jquery.bundle.js
file in the build output.
2.通过附加< script>来加载生成的脚本.懒惰地在DOM(< head>)中标记.
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);