javascriptファイルをDOMに追加する関数を作成しようとしていますが、新しく追加されたJSファイルが完全に読み込まれるまで残りのコードを待機させたいと考えています。このコードは正しく機能しませんが、これが私が達成しようとしていることの例です。
$(document).ready(function () {
var newScript = document.createElement("script");
newScript.setAttribute("type", "text/javascript");
newScript.src = "http://www.domain.com/script.js";
document.getElementsByTagName("body")[0].appendChild(newScript);
$(newScript).ready(function () { // This is the idea of what I'm trying to do, but this doesn't seem to actually wait until the new file is completely loaded.
foo.bar(); // foo is a new global variable which is declared in the newScript. This causes an error "foo is not defined".
// Here is where more code I wish to execute should continue.
});
});