开发者

jQuery ready function is called twice

This is my html

开发者_运维问答
<div id="projekt" style="position: relative; width: 90%;height:400px;"/>

 $("#projekt").ready(function() {

     .. do something with the div
 });

The problem is the ready function is called twice. What could be the reason ?


If you include your javascript file twice, it'll be executed twice. This doesn't show up clearly in firebug. The script panel (where I went to debug the javascript problem) will only show the file once in the dropdown. But if you look in the html or net panels you can see if there are multiples.

I had something like:

<script src="/scripts/project.js" type="text/javascript"></script>
<script src="/scripts/project.js" type="text/javascript"></script>

(This is similar to @chs answer, but not specific to rails.)


There's a bug which can cause this. Try updating or binding to the document instead of the div.


I found a solution to this problem.

You should use this code

$(document).bind("ready", MyDocumentReadyHandler)

instead of the code

$(document).ready(...);

You can read more about the "ready" function using this url.


I have seen this happen when I have an alert('...'); somewhere inside the .ready callback. This happens as recently as jQuery 1.5.2. Taking the alert out makes the code only run once.


No need to add application option at the following tag in config/application.rb config.action_view.javascript_expansions[:defaults] = %w(jquery application)

It will call applcation.js twice, so the functions also runs twice in your application


if you have a wrong src in iframe like <iframe src="../" ...></iframe>, the function ready() will be executed twice. Make sure you have a valid URL.

Ex.:

<iframe src="../something.html" ... ></iframe>


The correct way of invoking ready() is for document:

$(document).ready(function() {
    ...
});


I had the same issue. It went away when I moved my JS to another file and included it in the head tag instead of below the div I was working on.


You will run into the same issue when using JQM(jQueryMobile), but the issue in my case was having duplicate data-role="content" attributes. That attribute triggers the processing of everything inside the particular div or element with that attribute. In my case a .ready function was wrapped twice with it and therefore executed twice. Hope that helps someone.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜