Search code examples
javascriptexternalcdata

How to check if a script is loading external data?


I have this piece of code in a web site:

<div id="test">
  <script type="text/javascript">
    /*<![CDATA[*/
    parameter1 = 'whatever1';
    parameter2 = 'whatever2';
    parameter3 = 'whatever3';
    etc.
    /*]]>*/
  </script>
  <script src='external js file'></script>
</div>

This code is used to load an image in that site from an external source. When they (whoever they are) configure the external source properly, the div 'test' will show an image. If not, div will be blank.

Ok, now let's suppose that another div in that site must show a certain content depending if the image is loaded, and a different content if not.

The external source is not accessible/editable, so it's unknown if they (whoever they are) are sending data for a image to be load or not.

So, is there a way to foreknow/detect in the code if the div 'test' is loading data?

Edit 04/12/2016

Finally I have used this, thanks to cFreed suggestion:

var target = document.getElementById('test');
var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    //stuff;
  });    
});
var config = { attributes: true, childList: true, characterData: true };
observer.observe(target, config);

Solution

  • You might use MutationObserver.

    Here is a very simple application for your case.

    var observerConfig = {childList: true}, // only notify when children added
        targets = {
          test: false,
          ...other <div>s to observe
        },
        target, elem, observer;
    
    for (var target in targets) {
      elem = document.getElementById(target);
    
      // create and activate an observer instance
      observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
          // here we assume that the only changes are children addition
          // so we don't look at anything more precise
          targets[elem] = true;
        });
        observer.observe(elem, observerConfig);
      });
    }
    
    // then you can test targets['someTarget'] to know if it had been populated