簡體   English   中英

從另一個文件包含的文件中運行javascript函數

[英]running a javascript function from a file included by another file

我們使用document.write從另一個javascript文件中包含一個javascript文件。 在第一個javascript文件中是對第二個javascript文件中的函數的調用。 因此,我們收到一條錯誤消息:調試代碼時,'gMunchkin'未定義。 我做錯了什么,怎樣才能以這種方式調用'gMunchkin'?

我使用IE7來看演示: http//www.apus.edu/bin/r/u/test.htm

當您調用mktoMunchkin()時,瀏覽器很可能沒有完成下載munchkin.js。

你可以使用jQuery來加載 muchkin.js。

$.getScript('http://munchkin.marketo.net/munchkin.js', function() {
     //The code inside this anonymous function is executed by $.getScript() when the script has finished 
     //downloading.It is called a Callback function. It is required because 
     //getScript() does not block and will return before the javascript file is 
     //downloaded by the client
     //If the call to getScript was blocking, the client would be frozen until the 
     //js file was downloaded, which could be seconds and could lead the user 
     //to think the browser has crashed
     alert('Muchkin loaded. We can now use the Munchkin library.');
     mktoMunchkin("476-IFP-265");
});
//any code placed here will execute immediately. When this code is executed,
// munchkin.js may not have finished downloading. Hopefully you can see why 
//there is a need for the callback function in $.getScript().

這樣你可以保證munchkin.js在嘗試使用它的功能之前已完全下載。

當您使用document.write包含另一個腳本時,即使在實際獲取並包含其他腳本之前,您的主腳本也將繼續執行。 話雖如此, document.write被棄用了,你根本不應該將它用於任何目的。

有沒有理由不能直接將<script>標記添加到HTML中?

我寫了一個真正的異步接口,無論Munchkin js是否已經完成加載都可以使用 - https://github.com/ewebdev/marketo-munchkin-async

你可以讓父頁面做類似的事情

var doAllThisStuff = function() {
    mktoMunchkin();
};
var stillNeedToDoThis = null;
if (typeof mktoMunchkin == "function") {
    doAllThisStuff(); // Yay, we can do it right away!
} else {
    stillNeedToDoThis = doAllThisStuff; // We don't have mktoMunchkin yet. Better wait.
}

然后在新頁面的底部做這樣的事情

function mktoMunchkin() {
    // All kinds of code
}
if (typeof stillNeedToDoThis == "function") { // is anybody waiting for mktoMunchkin?
    stillNeedToDoThis();
    stillNeedToDoThis = null;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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