问题
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">
…
回答1:
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.
回答2:
What about a workaround... Did you know that a SCRIPT
tag at the end of the BODY
tag, is executed when everything before is loaded in the DOM
?
<body>
<!-- all your HTML here -->
<script>
//your starting Javascript code here
</script>
</body>
来源:https://stackoverflow.com/questions/6022357/why-does-window-load-work-but-not-document-ready