0

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?

shaosh
  • 657
  • 2
  • 8
  • 30
  • It looks like your problem is in a different file - I don't see your `cart` variable anywhere! – Krease Jun 05 '15 at 23:33
  • @Chris The cart is defined in the cartjs file, which is loaded by loadJsAsync. The cartjs file just defined this cart object and its functions/properties. I don't think the problem is in that file. – shaosh Jun 05 '15 at 23:44
  • It's also the only code that's trying to use it or somehow setting it to undefined. As is, we're left guessing to what could be going wrong. – Krease Jun 05 '15 at 23:50
  • 1
    Using the Object.observe method might provide an answer. See post by jakub here: [How to “break on property change” in chrome?](http://stackoverflow.com/questions/11618278/how-to-break-on-property-change-in-chrome) – Yogi Jun 06 '15 at 00:47
  • @Chris That is a library file and has 4000+ lines of code, it is really hard to put it here. If we just assume cartjs does not make the cart to undefined, what might be the possible explanation? – shaosh Jun 06 '15 at 00:47

0 Answers0