从另一个文件包含的文件中运行javascript函数

时间:2010-09-14 21:56:16

标签: javascript

我们使用document.write在另一个javascript文件中包含一个javascript文件。在第一个javascript文件中是对第二个javascript文件中的函数的调用。因此,我们收到一条错误消息:调试代码时,'gMunchkin'未定义。我做错了什么,怎样才能以这种方式调用'gMunchkin'?

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

4 个答案:

答案 0 :(得分:6)

当您调用mktoMunchkin()时,浏览器很可能还没有完成下载munchkin.js。

您可以使用jQuery to load 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在尝试使用它的功能之前已完全下载。

答案 1 :(得分:3)

当您使用document.write包含另一个脚本时,即使在实际提取并包含其他脚本之前,您的主脚本也将继续执行。话虽如此,document.write也被弃用了,你根本不应该将它用于任何目的。

您是否有理由不能直接将<script>标记添加到HTML?

答案 2 :(得分:0)

您可以让父页面执行类似

的操作
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;
}

答案 3 :(得分:0)

我写了一个真正的异步接口,无论Munchkin js是否已经完成加载都可以使用 - https://github.com/ewebdev/marketo-munchkin-async