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

Eva*_*van 2 javascript

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

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

小智 6

当您调用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().
Run Code Online (Sandbox Code Playgroud)

这样你可以保证munchkin.js在尝试使用它的功能之前已完全下载.