javascript - 使用Systemjs检测页面上是否加载了Angular

标签 javascript angular systemjs

更新:

这个问题专门讨论了 Angular 2,现在过时了。在发布时,没有办法检测它是否已加载到页面上。我没有测试过其他版本,但 Angular 8 现在有一种简单的方法来检测这一点,并已在下面的答案中指出。


我正在尝试找出一种好的(最好是最好的)方法来检测页面上是否加载了 Angular。

我看了一下这个问题:Ways to Detect whether AngularJS is loaded in the current page or not ,但答案只是说明要使用 window.angular,这是我尝试的第一件事(早在找到答案之前。)似乎 systemjs 导致 Angular 不在全局(窗口) 范围。

这是我的 html 文件的头部:

<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>

基于 this question ,以及我对 http2 的理解,我没有看到不使用 systemjs 的真正理由。

显然,我可能错了,systemjs 可能不是问题的原因;不管怎样,window.angular 返回 undefined,即使我正在查看我的 Angular 应用程序也是如此。

为了给你我们的用例,如果它有帮助,我们正在通过一个 init 文件加载一个 Angular 应用程序,该文件将在其他网站上使用(在大多数情况下我们不控制页面。)我们想要我们的 init文件,以便能够检测页面上是否已包含其他依赖项中的 angular2(和正确的版本)。如果他们没有,我们将动态添加他们没有的东西来满足我们的需要。 (这种方法可能还有一些其他问题,但我们会在到达那里时解决这些问题。)

总结

  1. 我们需要检测页面上是否加载了 Angular,以及什么版本。
  2. 使用 systemjs,window.angular 返回未定义。
  3. Angular 应用运行良好,没有问题。
  4. 对于 http2,我们认为没有必要不使用 systemjs 加载 Angular,但我们不反对在必要时更改它。

最佳答案

我使用以下方法成功检测到 Angular2:

window.ng

关于javascript - 使用Systemjs检测页面上是否加载了Angular,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34779126/

相关文章:

javascript - noUiSlider 多范围访问第一个句柄

javascript - Node +回调函数传参

javascript - jQuery:将元素移动到另一个元素并再次返回使该元素不可点击

angular - Angular2中圆括号、括号和星号有什么区别?

angular - ng6 : Dynamically form Variable names in html

javascript - 使用像 SystemJS 这样的模块加载器时,在 Safari 的 Web Inspector 中进行调试

javascript - systemJS 的相对动态加载,使用 ES6/Babel 语法

javascript - AJAX调用liferay门户

angular - 获取错误 "No provider for AlertIconAndTypesService!"

angular - "SyntaxError: Unexpected token export(…)"