Detect if Angular dependencies [angular-route, angular-resource, etc] are loaded for CDN fallback

和自甴很熟 提交于 2019-12-04 22:29:00

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;
    })(";

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>

This is what I use:

<script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.5.0/ui-bootstrap.min.js"></script>
<script>
  try { //try to load from cdn
    //use the name of the angular module here
    angular.module('ui.bootstrap');
  } 
  catch(e) { //error thrown, so the module wasn't loaded from cdn
    //write into document from local source
    document.write('<script src="sys/lib/ui-bootstrap.js"><\/script>'); 
  }
</script>

angular.module throws an error if there is no such module, which is exactly what we need to know! try/catch is great here.

(Variation on the answer from qntmfred.)

Instead of leaving that strange trailing open bracket, just use a normal immediately-invoked function.

The result will simply be that the Optimization Framework will wrap this in another set of parentheses, but leaves your C# much clearer.

angularjsRoute.CdnFallbackExpression = 
    @"(function() { 
        try { 
            window.angular.module('ngRoute');
        } catch(e) {
            return false;
        } 
        return true;
    })()";

Another variation...

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.14.3/ui-bootstrap-tpls.min.js"></script>
<script>
    try {
        window.angular.module('ui.bootstrap');
    }
    catch(e) {
        var script = document.createElement('script');
        script.src = 'lib/bootstrap/dist/js/bootstrap.js';
        document.getElementsByTagName('head')[0].appendChild(script);
    }
</script>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!