Javascript Race Conditions

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 am a developer based in Austin, Texas. I run a little theme shop called DevPress and help manage a WooCommerce shop with Universal Yums. Find me on twitter @devinsays.

1 Response

  1. 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