22

Let's say that I want to reference angularjs from a CDN but I would also like a fallback in case the call to the CDN fails, e.g. pointing to a local js-file. When it comes to JQuery I have seen examples where you would do something like this in javascript:

if(typeof jQuery == 'undefined') {
    ....
}

Is there anything similar for angularjs I can do?

4

9 Answers 9

33
if(typeof angular == 'undefined') {
    ....
}
16

I just opened the console by hitting F12 (or right-clicking and selecting Inspect element, then typed in angular.

If you get the message Object {version: Object, callbacks: Object}, angular is loaded.

If you get the message Uncaught ReferenceError: angular is not defined, angular is not loaded.

7

You can detect if the angular CDN (Content Delivery Network) has loaded the angular object correctly (i.e. this happens if the CDN is down) by testing if the angular JavaScript object is undefined.

You should then fallback to a local copy loaded using a document.write

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.12/angular.min.js"></script>
<script type="text/javascript">
    if(typeof angular == 'undefined') {
       document.write(unescape("%3Cscript type='text/javascript' src='/Scripts/angular.min.js'%3E%3C/script%3E"));
     }
<script type="text/javascript">
5
if(window.angular === undefined) {
    ....
}
3

For angular 2 and newer try

window.ng

in a console

1

I use this simple code before starting to know if the code has loaded

<body ng-app="">
 {{3  + 3}}
</body>

If this results in 6 then it means your angular is loaded else not.

1

For angular 11 you can use:

if(document.getElementsByTagName('app-root')[0].attributes['ng-version'] === undefined){
...
}
1
  • This is the cleanest solution that is future friendly... Commented Jul 4, 2023 at 14:51
0

Or do it like so :

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<script>(typeof angular != 'undefined') || document.write('<script src="js/angular.min.js")<\/script>')</script>
0

You can try something like this, this will return false when angular app has completed loading.

window.getAllAngularTestabilities()[0]._ngZone.hasPendingMacrotasks

Not the answer you're looking for? Browse other questions tagged or ask your own question.