I know the topic of "including a javascript file into another javascript file" has been discussed a lot. But my scenario is slightly different so I could not find an answer fitting to my problem.
Let's assume there are three files: test.html, starter.js and object.js
test.html simply includes starter.js using jQuery:
<html>
<head>
<script src="js/starter.js"></script>
</head>
<body>
<script src="jquery/jquery-1.9.1.js"></script>
<script>
$( document ).ready(function() {
$.getScript("js/starter.js", loadobject());
alert( "a" );
});
</script>
</body>
</html>
starter.js contains a function with $.getScript to include object.js and looks like this:
function loadobject() {
alert( "b" );
$.getScript("object.js", function(){
Object.init();
alert( "c" );
});
}
Finally the object.js contains an object like the following:
var Object = {
init: function () {
// . . .
},
searchString: function (data) {
// . . .
}
};
Object.init();
As far as I can see, when test.html is called in a browser it should include starter.js as soon as the document is ready. Furthermore, starter.js should load object.js when called.
But this seems to fail as the line alert( "object loaded" ); is never executed.
I also trial-and-errored a lot, for example replacing the line in starter.js $.getScript("object.js", function(){ with $.getScript("object.js", init(){, but I was not able to find a solution - although it might be simple. :(
How can I fix this and include the js file containing an object correctly?
Additionally how can a new Object be initialized and accessed within starter.js?
I think that I messed up with the function(), but actually I have no clue about that and appreciate any hint.
Thank you!
starter.jstwice? Once through HTMLscripttag, once throughgetScript(). What is your goal with doing all this stuff? I don't see the point.scripttag, thegetScript()function throws an error saying that the variableloadobjectis undefined. With thescripttag this error does not occur.getScript(). Simply doloadobject()instead of$.getScript("js/starter.js", loadobject());. At that time, starter.js is already loaded.