Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect whether Angular is loaded on a page when using Systemjs

UPDATE:

This question was specifically talking about Angular 2, and is now out of date. At the time of posting, there was not a way to detect whether it was loaded on the page. I have not tested other version, but Angular 8 now has an easy way to detect this and has been pointed out in the answer below.


I'm trying to figure out a good (preferably the best) way to detect whether or not Angular is loaded on the page.

I took a look at this question: Ways to Detect whether AngularJS is loaded in the current page or not, but the answer simply states to use window.angular, which is the first thing I tried (long before finding that answer.) It seems as though systemjs is causing Angular to not be in the global (window) scope.

Here is the head of my html file:

<script src="client/node_modules/angular2/bundles/angular2-polyfills.js"></script>
<script src="client/node_modules/systemjs/dist/system.src.js"></script>
<script src="client/node_modules/rxjs/bundles/Rx.js"></script>
<script src="client/node_modules/angular2/bundles/angular2.dev.js"></script>
<link rel="stylesheet" href="client/styles/main.css"/>

<script>
  System.config({
    packages: {        
        client: {
            format: 'register',
            defaultExtension: 'js'
        }
    }
  });
  System.import('client/app')
        .then(null, console.error.bind(console));
</script>

Based on this question, and my understanding of http2, I don't see a real reason to not use systemjs.

Obviously, I may be wrong, systemjs may not be the cause of the issue; regardless, window.angular returns undefined even though I'm looking at my Angular app.

To give you our use case, in case it helps, we are loading an angular app via an init file that will be used on other websites (where we don't control the page in most cases.) We want our init file to be able to detect whether angular2 (and the proper version) among other dependencies are already included on the page. If they are not, we are dynamically adding what they don't have for our need. (There may be some other issues with this approach, but we'll tackle those issues when we get there.)

Summary

  1. We need to detect whether Angular is loaded on the page, and what version.
  2. Using systemjs, window.angular is returning undefined.
  3. The Angular app runs fine and without issue.
  4. With http2, we don't see the need to not load Angular using systemjs, but we are not opposed to changing that if necessary.
like image 334
Jacques ジャック Avatar asked Jan 13 '16 23:01

Jacques ジャック


1 Answers

I had success detecting Angular2 using:

window.ng
like image 97
mwilcox Avatar answered Oct 23 '22 23:10

mwilcox