Andrew Heins

default-image

Loading Dependencies Reliably in Javascript

For Those Slow-Loading Scripts


I’ve been playing with Canvas recently and got to try out the excanvas library in order to extend 2d canvas functionality to IE. I can’t speak highly enough about excanvas by the way, try it out if you get the opportunity.

Anyway, I found myself in a situation where I was loading excanvas in the header, and drawing on the canvas inside of jQuery’s (document).ready(), but excanvas hadn’t always loaded by the time jQuery started to draw.

I learned this little trick from Paul Irish’s “10 Things I Learned from the jQuery Source” (watch it if you haven’t, it’s awesome.)

Here, we’re using setInterval to check to see if excanvas has loaded every 1/10th of a second, and if it has, then doing our canvas work.

$(document).ready(function() {
  var canvas = $("#myCanvas")[0],
  ctx, interval, i = 0, MAX_TRIES = 10;

  (function draw() { // Self-executing function starts us off
    if(canvas.getContext){ // If excanvas has loaded...
    // draw stuff
    } else {
      if(i < MAX_TRIES) {
        i++;
        interval = setInterval(draw, 100);
      }
      else {
        clearInterval(interval);
        // Fallback code here
      }
    }
  })();
});

You can add an alert(i); in once canvas loads to let you know how many tries it took for your dependency to load. I haven’t run into a situation where it’s taken more than a couple of tries, but it depends on latency.

Not exactly a groundbreaking script, but certainly something that helped me out.

If you’ve got any questions or comments, you can leave a note below or catch me on Twitter.


Join the Conversation!