简体   繁体   English

在函数中参考外部JavaScript文件

[英]Reference External JavaScript File in Function

Is it possible to reference a JavaScript file inside of a JavaScript function? 是否可以在JavaScript函数内部引用JavaScript文件?

Therefore i am wanting to convert this: 因此,我想将其转换为:

<script type="text/javascript" src="http://crypto-js.googlecode.com/files/2.5.3-crypto-sha1-hmac.js"></script>
<script type="text/javascript">

var hmacString = Crypto.HMAC(Crypto.SHA1, "Message", "Secret Passphrase", { asString: true });

</script>

In to: 到:

function hmac (input){

  var hmacString = Crypto.HMAC(Crypto.SHA1, "Message", "KEY", { asString: true });

  return hmacString;

}

I am using a tool called Cast Iron, which therefore restricts JavaScript down to only a function, but i need to call an external file, to load the needed functionality. 我正在使用一个称为Cast Iron的工具,因此将JavaScript限制为仅一个函数,但是我需要调用一个外部文件来加载所需的功能。

Is this even possible? 这有可能吗?

If I understand correctly, yes you can access functions and classes from one JS file as long as the other class was loaded before you attempt to access it. 如果我理解正确,是的,您可以从一个JS文件访问函数和类,只要在尝试访问另一个JS文件之前就已对其进行加载。

So, if some-javascript-file.js has a function named getThings() , then you can do this: 因此,如果some-javascript-file.js getThings()具有名为getThings()的函数,则可以执行以下操作:

<script type="text/javascript" src="http://cdn.example.com/js/some-javascript-file.js"></script>
<script type="text/javascript">
    var things = getThings(); // getThings is a publicly accessible function in an external class.
</script>

OK the screenshot kind of helps. OK屏幕快照有帮助。 It seems you want something from an external JS file, and to manipulate it inside this function. 似乎您需要外部JS文件中的内容,并在此函数中对其进行操作。

So you could have one javascript file with: 因此,您可以使用以下一个javascript文件:

var foo = 'foo'; //this is in the global scope

and then your other file has: 然后您的其他文件具有:

function hmac(key){
    alert(document.foo);
}

should access what you want 应该访问您想要的

Yes, you can load other js files with javascript. 是的,您可以使用javascript加载其他js文件。 Depending on the load state where your function is executed, you may either use 根据执行函数的加载状态,可以使用

document.write('<script type="text/javascript" src="http://crypto-js.googlecode.com/files/2.5.3-crypto-sha1-hmac.js"'+'><'+'/script>"');
// loads synchronouly and executes
Crypto.HMAC(...); // is available here

Watch out that document.write breaks the whole page once your DOM is loaded. 请注意,加载DOM后,document.write会破坏整个页面。 You can also use: 您还可以使用:

var s = document.createElement("script");
s.type = "text/javascript";
s.src = "http://crypto-js.googlecode.com/files/2.5.3-crypto-sha1-hmac.js";
s.onload = function() {
    // the file should be executed now so
    Crypto.HMAC(...); // is available here
};
document.head.appendChild(s); // load asychronously

See also Load js from external site on fly 另请参阅从外部站点动态加载js

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

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