首页 > 解决方案 > 如何在 javascript 中导入在 html 中引用的这个库?

问题描述

我在 AngularJS 中有一个脚本,只有当我有这一行时才会运行

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.js">

现在我希望我的方法有自己的 javascript 文件,所以我可以引用它,但没有导入或任何东西。

传统上,在您导入链接的情况下,这是如何完成的?我应该去该链接下载该文件并将其导入项目吗?

标签: angularjs

解决方案


要在您的一个文件中执行此操作,您需要<script>手动从标签加载文件。这不是太难。通过添加脚本标签,您必须等待它加载,直到您的代码运行。这是您将如何做到的。在文件的顶部,您将添加以下内容。

// Create a script tag manually
var angularJsScriptTag = document.createElement('script');

// Set the src on the script tag to your CDN version of AngularJS
angularJsScriptTag.src = "https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.js";

// The script won't load until you append it to the document. So append it to the head
document.head.appendChild(angularJsScriptTag);

// Add a listener for when the AngularJS had loaded. Once it's loaded, run your own code. 
angularJsScriptTag.onload = function() {
  // Call a function to execute your code in this onload callback. 
  // This code won't run until that AngularJS script has loaded. 
}

推荐阅读