I’m trying to create my first javascript file that loads asynchronously, but am having trouble with calling functions from the object afterwards. Below is my example javascript file exampletest.js…
(function(){
var example = {
test : function () {
alert("test function called");
}
};
window.example = example;
})();
I then try to call this file using the following code.
(function(doc, example) {
window.example = example;
var script = doc.createElement("script");
script.type = "text/javascript";
script.async = true;
script.src = "http://www.example.com/exampletest.js";
var scriptTag = doc.getElementsByTagName("script")[0];
scriptTag.parentNode.insertBefore(script, scriptTag);
})(document, window.example || []);
example.test();
When I run this script I get the error “Uncaught TypeError: Object has no method ‘test'”
If I call the method after the page has loaded, say on a link click, the test method is properly called and I get my alert box.
I’ve been searching around trying to understand this better but have so far been out of luck. I’m trying to better understand how I could call a function without getting the has no method ‘test’. Is there a way to push the function call after the javascript has loaded without junking up the call itself so it stays example.test();?
Just check whether the function exist before you call it.
Try this :
Note: As the JavaScript is loaded asynchronously,
window.onloadwon’t work.Update
The whole purpose of having
asyncis to load the page without waiting for the scripts to load. You cannot have both.This won’t work
but this will work, as the execution waits for the file to load