Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does $(window).load() work but not $(document).ready()?

I'm working with a rails 3 app, and I want to use a sortable list. I'm working with the method shown here. My app uses JQuery, and there's a js file included in my app's layout that calls $(document).ready() to set up some visual stuff. That seems to be working fine.

However, when I attempt to call $(document).ready() in my view template via content_for :javascript to set up the sortable list, that code never fires. I do have the requisite yield :javascript call in my layout file, and if I load the page and look at the source everything looks fine. The code never runs, though – i.e. this instance of $(document).ready() never fires.

I've just found that if I replace $(document).ready() with $(window).load() then my js code runs.

So my question is: Why would $(document).ready() fail and $(window).load() work?

Code

This works:

<% content_for :javascript do %>

<script>
   $(window).load(function(){
     alert('it works!');
   });
</script>
<% end %>

This doesn't work

<% content_for :javascript do %>

<script>
   $(document).ready(function(){
            alert('it works!');
   });
</script>
<% end %>

Here's the Layout

<!DOCTYPE html>
<html>
  <head>
    <title><%= content_for?(:title) ? yield(:title) : "Untitled" %></title>

    <!-- Reset Stylesheet -->
      <%= stylesheet_link_tag "reset" %>
        <!-- Main Stylesheet -->
      <%= stylesheet_link_tag "style" %>
        <!-- Invalid Stylesheet -->
      <%= stylesheet_link_tag "invalid" %>

        <%= javascript_include_tag :defaults, "nested_form", "DD_belatedPNG_0.0.7a", "simpla.jquery.configuration", "facebox", "jquery-ui.min" %>
        <%= yield :javascript %>

    <%= yield(:head) %>
    <%= csrf_meta_tag %>

  </head>
  <body onload="initialize()"><div id="body-wrapper">
…
like image 807
CharlieMezak Avatar asked Oct 25 '22 11:10

CharlieMezak


1 Answers

There is a conflict with the body's onready= callback registered. See the jquery docs. You must remove the <body onload="initialize()">.

http://api.jquery.com/ready/

Also a possibility is a resource being loaded very VERY slowly. However the first is more likely.

.ready is triggered when resources are loaded. It is possible a resource may be perpetually in a wait state because the server never closed the socket when sending the resource to the browser. Use firebug's network monitor tool to track down if this is the case.

like image 112
Dmitriy Likhten Avatar answered Oct 27 '22 10:10

Dmitriy Likhten