问题描述
我在ASP.NET MVC 4上使用Angular JS,并且我正在使用脚本包从cdn加载,并且在cdn发生故障的情况下也从原始服务器加载:
I'm using Angular JS on ASP.NET MVC 4 and I am using script bundles to load from a cdn and also load from the origin server in case of a cdn failure like so:
var jQuery = new ScriptBundle("~/bundles/scripts/jquery",
"//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js") // CDN
.Include("~/Scripts/jquery-{version}.js"); // Local fallback
jQuery.CdnFallbackExpression = "window.jQuery"; // Test existence
bundles.Add(jQuery);
和
var angular = new ScriptBundle("~/bundles/scripts/angular",
"//ajax.googleapis.com/ajax/libs/angularjs/1.2.0-rc.2/angular.min.js")
.Include("~/Scripts/angular.js");
angular.CdnFallbackExpression = "window.angular";
bundles.Add(angular);
分别使用window.jQuery和window.Angular来检测jQuery或AngularJS是否存在是相当容易的. ASP.NET捆绑机制评估CdnFallbackExpression文本以查看是否需要回退到原始服务器.
It is fairly easy to detect if jQuery or AngularJS exist using window.jQuery and window.Angular respectively. The ASP.NET bundling mechanism evaluates the CdnFallbackExpression text to see if it needs to fall back to the origin server.
但是,在更高版本的AngularJS中,其他模块(例如ngRoute和ngResource)被分离到各自的文件中,由开发人员自行决定加载.
However, in later versions of AngularJS, other modules such as ngRoute and ngResource are separated into their own files to be loaded at the developers discretion.
如何检测是否已加载其他AngularJS模块?我可以在控制台中键入什么以查看ngAnimate,ngRoute,ngResource等是否成功从CDN加载?
How do I detect if other AngularJS modules are loaded? What could I type in the console to see if ngAnimate, ngRoute, ngResource, etc. succeeded in loading from the CDN?
推荐答案
以下是与OP中提供的Microsoft Optimization Framework专门配合使用的一种方法
Here is an approach that works specifically with the Microsoft Optimization Framework as you provided in the OP
angularjsRoute.CdnFallbackExpression = @"
function() {
try {
window.angular.module('ngRoute');
} catch(e) {
return false;
}
return true;
})(";
此表达式本身不是有效的javascript,但是MS Optimization Framework使用此表达式,并最终在页面上产生以下输出.现在,我们有了一个有效的自执行javascript函数,该函数根据angular模块是否加载而返回true或false.
This expression is not valid javascript itself, but the MS Optimization Framework uses this and eventually produces the following output to the page. Now we have a valid self-executing javascript function that returns true or false based on whether the angular module loads.
<script>(
function() {
try {
window.angular.module('ngRoute');
}
catch(e) {
return false;
}
return true;
})()||document.write('<script src="/bundles/scripts/angularjs-route"><\/script>');</script>
这篇关于检测是否为CDN后备加载了Angular依赖项[angular-route,angular-resource等]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!