簡體   English   中英

在函數中參考外部JavaScript文件

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM