Fix race condition in JS loading.

Not 100% sure that this fix works in all cases, but it seems to be
better that the previous solution.