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?

Stig Perez
  • 3,595
  • 4
  • 23
  • 36

9 Answers9

33
if(typeof angular == 'undefined') {
    ....
}
followben
  • 9,067
  • 4
  • 40
  • 42
Doron Segal
  • 2,242
  • 23
  • 22
15

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.

maudulus
  • 10,627
  • 10
  • 78
  • 117
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">
Liam
  • 27,717
  • 28
  • 128
  • 190
5
if(window.angular === undefined) {
    ....
}
Luke
  • 11,426
  • 43
  • 60
  • 69
pixelbyaj
  • 1,178
  • 1
  • 9
  • 22
3

For angular 2 and newer try

window.ng

in a console

Eric Herlitz
  • 25,354
  • 27
  • 113
  • 157
1

For angular 11 you can use:

if(document.getElementsByTagName('app-root')[0].attributes['ng-version'] === undefined){
...
}
alastairtree
  • 3,960
  • 32
  • 49
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>
Otman Bouchari
  • 196
  • 1
  • 6
0

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.

Black Mamba
  • 13,632
  • 6
  • 82
  • 105
0

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

window.getAllAngularTestabilities()[0]._ngZone.hasPendingMacrotasks
Ram
  • 451
  • 10
  • 18