In the html page I have some js code, which loads an js file called cartjs in $(window).load like below:
<script>
//var cart = {};
var loadJsAsync = {
load: function(sourceUrl, id) {
var js, fjs = document.getElementsByTagName('script')[0];
var that = this;
if (document.getElementById(id)) {
that.callbacks.forEach(function (fn, index) {
console.log(fn, index);
fn();
});
return;
}
js = document.createElement('script');
js.type = 'text/javascript';
js.ansyc = true;
js.id = id;
js.src = sourceUrl;
fjs.parentNode.insertBefore(js, fjs);
$('#' + id).on('load', function() {
that.callbacks.forEach(function (fn, index) {
console.log(fn, index);
fn();
});
});
},
callbacks: []
};
$(window).load(function () {
loadJsAsync.load("<%= ScriptSourceUrl %>", 'cartjs');
});
</script>
The callbacks is where I put functions dependent on the Object cart defined in cartjs. When I refresh the entire page, everything is good, and there are no dependency problems.
When an ajax call is fired to partially update some data in the page, the #cartjs script tag is still there, while the cart Object will become undefined and the code
if(document.getElementById(id)) {
that.callbacks.forEach(function (fn, index) {
console.log(fn, index);
fn();
});
return;
}
will also complain the cart Object is undefined.
However, if I define a global cart object before the loadJsAsync by removing the comment in the first line, the cart object will no longer become undefined after refresh, and the depending functions will no longer complain.
Does anyone kindly know how to explain it?