[英]Reference External JavaScript File in Function
是否可以在JavaScript函数内部引用JavaScript文件?
因此,我想将其转换为:
<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>
到:
function hmac (input){
var hmacString = Crypto.HMAC(Crypto.SHA1, "Message", "KEY", { asString: true });
return hmacString;
}
我正在使用一个称为Cast Iron的工具,因此将JavaScript限制为仅一个函数,但是我需要调用一个外部文件来加载所需的功能。
这有可能吗?
如果我理解正确,是的,您可以从一个JS文件访问函数和类,只要在尝试访问另一个JS文件之前就已对其进行加载。
因此,如果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屏幕快照有帮助。 似乎您需要外部JS文件中的内容,并在此函数中对其进行操作。
因此,您可以使用以下一个javascript文件:
var foo = 'foo'; //this is in the global scope
然后您的其他文件具有:
function hmac(key){
alert(document.foo);
}
应该访问您想要的
是的,您可以使用javascript加载其他js文件。 根据执行函数的加载状态,可以使用
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
请注意,加载DOM后,document.write会破坏整个页面。 您还可以使用:
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
另请参阅从外部站点动态加载js
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.