1

I run into this issue from time to time and I don't know how to solve it. Here's my code that fails:

function on_lightbox_open() {

    system.contextBrowserInit();

    updateUrl(year + '/' + month + '/' + id);
    ads.reload();
    system.analytics.reload();

    FB.XFBML.parse($('#bottom_flap .fb_like').get(0)); // facebook
    $.ajax({ url: 'http://platform.twitter.com/widgets.js', dataType: 'script', cache: true });

    $('#lightbox .close').live('click', function(){
        $.modal.close();
    });
}

If I add an alert at the begining like so:

function on_lightbox_open() {

    alert('i work now');

    system.contextBrowserInit();

    updateUrl(year + '/' + month + '/' + id);
    ads.reload();
    system.analytics.reload();

    FB.XFBML.parse($('#bottom_flap .fb_like').get(0)); // facebook
    $.ajax({ url: 'http://platform.twitter.com/widgets.js', dataType: 'script', cache: true });

    $('#lightbox .close').live('click', function(){
        $.modal.close();
    });
}

It magically works. How to make it work without an annoying random alert?

  • 4
    Race condition. Your alert introduces a delay, which gives some other process time to execute first. Without the alert, that other process would execute later. – Jim Blackler Mar 01 '12 at 21:03
  • 3
    It looks like a race condition involving some other piece of your code. – John Pick Mar 01 '12 at 21:03
  • @Jim Blackler Putting the code inside a set time out with a delay of 1000 milliseconds worked. What would be a good number to reduce that too that will still work on most hardware? Could I get away with like 50 milliseconds or maybye less? –  Mar 01 '12 at 21:10
  • 3
    @JakeRow123: Ideally, you would chain the callbacks correctly and not try to have an arbitrary and bug-prone delay like that. – hugomg Mar 01 '12 at 21:12

2 Answers2

1

Perhaps your use of .live() requires a fully loaded document and the alert just buys the browser some extra time. Try surrounding with $(document).ready();

Source: jQuery-driven app. won't work without alert()

Community
  • 1
  • 1
Alfabravo
  • 7,493
  • 6
  • 46
  • 82
0

Instead of:

<script>
    system.contextBrowserInit();
    //etc
</script>

Try this (HTML doctype):

<script defer>
    system.contextBrowserInit();
    //etc
</script>

Correct syntax for XHTML doctype is

<script defer="defer">
    system.contextBrowserInit();
    //etc
</script>
Chris Sobolewski
  • 12,819
  • 12
  • 63
  • 96