I have html with :
<script src="/js/app.js"></script>
in app.js I have function foo:
function foo() { console.log("foo") }
Then I have jquery and use it's method .load to load external html content:
$("#modal-wrapper").load("/modal_dialog_ajax", function () {
// Some logic
});
Output of /modal_dialog_ajax looks like:
<div>Some markup</div>
<script type="text/javascript">
foo();
</script>
Javascript is executed fine but call of foo() is undefined in the scope of this html.
Why Js inside ajax loaded html content does not see global functions defined on the page?
Workarounded this using window global object:
function foo() { console.log("foo") }
window.foo = foo;
And then call it as
window.foo();
But not sure it is a good practice.