开发者

running a javascript function from a file included by another file

We are including a javascript file from within another javascript file using document.write. Within the first javascript file is a call to a function in the second javascript file. As a result, we are getting an error message: 'gMunchkin' is undefined when I debug the code. What am I doing wrong, and how can 'gMunchkin' be called in this way?

I used IE7 to see the Demo: http://www.apu开发者_运维技巧s.edu/bin/r/u/test.htm


It's very possible the browser hasn't finished downloading munchkin.js when you make the call to mktoMunchkin().

You could use 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().

This way you are guaranteed munchkin.js is fully downloaded before trying to use it's functions.


When you include another script using document.write, your main script will continue executing, even before the other script has actually been fetched and included. That being said, document.write is deprecated as well and you shouldn't be using it for any purpose at all.

Is there a reason you can't directly add the <script> tag to your HTML?


You could have the parent page do something like

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.
}

Then at the bottom of the new page do something like this

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


I wrote an real async interface that can be used regardless of Munchkin js has finished loaded or not - https://github.com/ewebdev/marketo-munchkin-async

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜