Kylo
Kylo

Reputation: 2320

How to suspend execution of javascript?

Is there any way to suspend execution of javascript until whole page is loaded in a browser? I am updating a div at the bottom of the document using AJAX but when I click this link before whole page is loaded I get an error...

<%= link_to_remote 'Update', :update => 'div_at_the_bottom', :url => { :usual_stuff } %>

Upvotes: 1

Views: 877

Answers (3)

Crescent Fresh
Crescent Fresh

Reputation: 116998

Disable the generated link and enable it when the dom has loaded:

  1. Disable the link:

    <%= link_to_remote 'Update', 
            { :update => 'div_at_the_bottom', :url => { :usual_stuff } },
            { :disabled => 'disabled', :id => 'update-trigger' }
    %>
    

    (note that to be able to pass this extra option to link_to_remote you need to make the [2nd] "options" hash explicit by wrapping it with curlies {}. Extra help on this)

  2. Then somewhere (anywhere after the prototype js lib has been included) enable the link when the DOM has loaded (this is similar to what everyone has been saying to do so far):

    <script>
    $(document).observe('dom:loaded', function() {
        $('update-trigger').disabled = false
    })
    </script>
    

This solution is also semantically agreeable, if that matters to you (it does to me).

Upvotes: 2

DisgruntledGoat
DisgruntledGoat

Reputation: 72560

The simplest way is to do everything on window.onload:

window.onload = function() {
  // do everything here
}

You could also put your javascript right at the end of the page, before </body>. That way whatever objects you're operating on are guaranteed to be in the DOM.

As others have said, some JS frameworks have a nice method of running JS as the DOM loads. The main advantage of this is you don't get the JS equivalent of "flash of unstyled content", i.e. seeing an element in one (possibly ugly) form, then changing once the full page has loaded.

Upvotes: 3

code_burgar
code_burgar

Reputation: 12323

If you go for a JavaScript library like jQuery you can easily bind any javascript code to the DOM ready event and avoid issues of this kind.

Upvotes: 1

Related Questions