在AngularJS控制器的一个延迟加载外部JavaScript [英] Lazy-load external JavaScript in one of AngularJS controller

查看:160
本文介绍了在AngularJS控制器的一个延迟加载外部JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的一些路由从外部JS需要的功能。我不想一次加载所有这些,因为只需要在某些航线的JS(如 /上传需要一些JS的照片上传, /照片需要另一个JS的灯箱, /滑稽 JS需要动画的东西,等等)。

Some of my routes needs functionality from external JS. I don't want to load them all at once since those JS are needed only in certain routes (e.g. /upload needs some JS for photo uploading, /photos needs another JS for lightbox, /funny needs JS for animation stuff, etc).

什么是对延迟加载这些外部JavaScript的最佳实践?

What's the best practice for lazily loading those external JavaScripts?

这些路由可以多次访问(例如,用户可以到 /上传然后 /照片然后 /上传再次)

Those routes can be accessed multiple times (e.g. user can go to /upload then /photos then /upload again)

推荐答案

我知道要处理这样使用路由的解析方法的情况下,唯一的方法。这种方法可以被用来定义该路由的控制器被实例化之前被加载的依赖关系。一个可能出现的不同的返回类型此方法是一种承诺。因此,你可以用它来启动异步加载你的外部JavaScript code和返回是,只要你的外部脚本加载解决的承诺。

The only way I know to handle cases like this is using the "resolve" method of a route. This method can be used to define a dependency to be loaded before the route's controller is instantiated. One of the different possible return types of this method is a promise. Thus you might use this to start loading your external JavaScript code asynchronously and return a promise that is resolved as soon as your external scripts are loaded.

此文档可以在这里找到: HTTPS://docs.angularjs。组织/ API / ngRoute /供应商/ $ routeProvider 中的当部分。

The documentation for this can be found here: https://docs.angularjs.org/api/ngRoute/provider/$routeProvider in the "when" section.

这篇关于在AngularJS控制器的一个延迟加载外部JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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