2

I have a number of jQuery addons used by my Rails app. Almost all pages use the jQuery.cookies extension to determine whether a specific element should be shown or hidden.

This addin was originally its own file under assets/javascripts, and loaded using the following manifest:

//= require jquery
//= require jquery_ujs
//= require jquery-ui
//= require_self
//= require_directory . //there is a subdirectory i'm ignoring, but jquery.cookies isn't in it

On Internet Explorer, jquery.cookies.js was being evaluated on every page that required it except for two, where the cookies object was not being added to the jQuery. These pages included the same javascripts as any other page on my app:

javascript_include_tag('application')

On the affected pages, when the following code was evaluated, it was throwing an error like 'Object doesn't support this property or method' concerning the cookie method:

if ($.cookie("showHero") == 'true' || $.cookie("showHero") == null) {
    $('#hero').css('display', 'block');
} else {
    $('#hero').css('display', 'none');
}

Moving the contents of jQuery.cookies.js to the top of application.js, before calling $(document).ready() seems to alleviate this symptom and allow the javascript to run properly, but I'm afraid I haven't fixed the real problem.

This would occur on both development and production with precompiled assets.

Neither of these pages introduces any javascript that's unique to the page, why might jQuery.cookies fail to be evaluated in such a narrow case? Is there a convention for handling multiple distinct javascript files I'm not aware of that I might have missed?

Edit

I take it back; moving the contents of jquery.cookies into application.js only appears to be working the first time the page is loaded. Subsequent reloads exhibit the same behavior. At a complete loss.

4

1 に答える 1

1

FB.init()このページでのみ実行される条件が存在することが判明しました。これ$は、cookie オブジェクトへのアクセスに使用されていたシンボルを破壊したようです。

これがなぜなのか完全にはわかりません。FBプロトタイプ ライブラリを使用した結果であるFBか、何らかの理由でオブジェクトが原因で jQuery が再初期化された可能性があります。

別の関数内で囲むことによって js ファイルの内容を変更すると、JavaScript$(document).ready()の両方のセットを実行できます。jQuery.noConflict()jQuery$js.erb

//= require jquery
//= require jquery-ujs

(function($) { // the $ is explicitly set to jQuery for this scope
  $(document).ready(function() {

    // no more complaints that 'cookies is not a method of $'
    if ($.cookies('showHero') == true ) {
       // do something
    }
  });
})(jQuery); 
于 2012-05-09T23:24:42.060 に答える