Created in Gran Turismo 5's Photo Mode and enhanced with Adobe Photoshop CS5.

Javascript Race Conditions

Posted

I’ve encountered a couple issues with javascript race conditions this last week, especially in the Chrome browser.

A race condition is where the timing of one event is critically tied to other events which need to happen before it in sequence. In both situations I was enqueing a javascript file, but I also had inline javascript that wouldn’t work until the enqueued file had completely finished loading.

What’s odd is that these scripts worked fine in Firefox and Internet explorer, it just wasn’t loading correctly in Chrome, perhaps because its faster javascript rendering. To fix the issue, I added a check in the inline javascript which looks for the function it relies on in the enqued javascript. If that function isn’t present yet, it will delay the load of the inline script until it’s ready.

In this example, the function I was waiting for was AjaxUpload. Here’s the code that does the check:

// Race condition to make sure js files are loaded
if (typeof AjaxUpload != 'function') {
     return ++counter < 6 && window.setTimeout(init, counter * 500);
}

I’m by no means a javascript expert, but I thought I’d share this in case other folks are having similar issues. Has this come up in any of your projects?

About Devin

I'm a WordPress developer based in Austin, Texas. Follow my projects on GitHub, or more general WordPress ramblings as @devinsays on twitter.

One thought on “Javascript Race Conditions

  1. Ben Giordano wrote:

    Devin,

    I had some js issues with chrome a while back as well, mine were a bit more novice, had two scripts running in the same header, one was auto prioritized over the other. This is great though, I’ll keep it in mind if I run into this in the future.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>