Jon
Jon

Reputation: 154

JS wait for content to finish loading before running function

I'm running a webpage in some graphics playout software. The function update() is automatically called by the graphics software when the page initially loads up, however I need to wait for the animation library to finish loading before the code in update() executes.

animation.addEventListener('DOMLoaded', function () {
  console.log('Animation ready');
});

// This is automatically called by the graphics renderer on page load.
function update(data) {
  // update the data in the animation...
};

I've come up with a workaround using setInterval that check if the animation has loaded before running the update code:

var animationLoaded = false;
animation.addEventListener('DOMLoaded', function() {
  console.log('Animation ready');
  animationLoaded = true;
});

// This is automatically called by the graphics renderer on page load.
function update(data) {
  var updateInterval = setInterval(function() {
    if (animationLoaded) {
      clearInterval(updateInterval);
      // update the data in the animation...
    }
  }, 10);
}

I feel there is a much better way of doing this, maybe using async/await? but I am unsure how to do this?

Upvotes: 0

Views: 670

Answers (1)

Obzi
Obzi

Reputation: 2390

An idea, may not be the best :

  • on the update function, if DOMLoaded has been trigger then do your job, else save the data parameter
  • on the DOMLoaded function, call update with the saved datas (if set)
var animationLoaded = false;
var animationData = null;

animation.addEventListener('DOMLoaded', function() {
  animationLoaded = true;
  if (animationData !== null) {
    update(animationData);
  }
});

// This is automatically called by the graphics renderer on page load.
function update(data) {
  if (animationLoaded) {
    // update the data in the animation...
  } else {
    animationData = data;
  }
}

Upvotes: 1

Related Questions