简体   繁体   English

如何在 JavaScript 中导入它?

[英]How can I import this in JavaScript?

I have a JavaScript function that runs in an HTML file, but in order to avoid "angular is not defined", I put the following before my HTML script I have a JavaScript function that runs in an HTML file, but in order to avoid "angular is not defined", I put the following before my HTML script

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

Is there a way to do this in a actual JavaScript file?有没有办法在实际的 JavaScript 文件中执行此操作? I want to write my function in a JavaScript file not HTML so I can't use src HTML code.我想在 JavaScript 文件中写我的 function 而不是 HTML 所以我不能使用src Z4C4ZDBB15FCA2E78AAA4Z 代码

I tried copying all the code and putting it in a file and referencing the file in the JavaScript but it doesn't work.我尝试复制所有代码并将其放入文件中并在 JavaScript 中引用该文件,但它不起作用。

Any workarounds?任何解决方法?

Something like:就像是:

    const libname = require("https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.js") 

Should import the.js file into your project.应该将 .js 文件导入到您的项目中。

There are a variety of solutions to this problem and you should review how scripts load and the onready events for an html document.此问题有多种解决方案,您应该查看 html 文档的脚本加载方式和 onready 事件。 One simple solution would be coding your custom function to be called in an approach something like this:一个简单的解决方案是对您的自定义 function 进行编码,以便以如下方式调用:

<script onload="myCustomFunction();"
        src ="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.js" >
</script>`

Of course, there are really many different approaches and I would consider this one only to use in a quick and dirty situation.当然,确实有很多不同的方法,我认为这种方法只用于快速而肮脏的情况。

A simple technique that I use to load dependencies is to dynamically append them to the document head and use a load EventListener to run my code after the external script has finished loading.我用来加载依赖项的一种简单技术是动态地将它们 append 到文档头,并在外部脚本完成加载后使用load EventListener 来运行我的代码。

let s = document.createElement('script');
s.src = 'https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.js';
s.addEventListener('load', init);
document.head.appendChild(s);

function init() {
  // your code here
}

Source: I build a lot of plugins/widgets.资料来源:我构建了很多插件/小部件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM