使用Rails 3.1,您在哪裏放置“特定於頁面”的JavaScript代碼?

本文翻譯自:Using Rails 3.1, where do you put your “page specific” JavaScript code?

To my understanding, all of your JavaScript gets merged into 1 file. 據我所知,您的所有JavaScript都合併爲1個文件。 Rails does this by default when it adds //= require_tree . Rails在添加//= require_tree .時默認執行此操作//= require_tree . to the bottom of your application.js manifest file. application.js清單文件的底部。

This sounds like a real life-saver, but I am a little concerned about page-specific JavaScript code. 這聽起來像是一個真正的生命保護程序,但我有點擔心特定於頁面的JavaScript代碼。 Does this code get executed on every page? 此代碼是否在每個頁面上執行? The last thing I want is for all of my objects to be instantiated for every page when they are only needed on 1 page. 我想要的最後一件事是,只需要在1頁上需要爲每個頁面實例化我的所有對象。

Also, isn't there potential for code that clashes too? 此外,代碼是否也存在衝突的可能性?

Or do you put a small script tag at the bottom of the page that just calls into a method that executes the javascript code for the page? 或者你是否在頁面底部放了一個小script標籤,只是調用一個執行頁面javascript代碼的方法?

Do you no longer need require.js then? 那你不再需要require.js了嗎?

Thanks 謝謝

EDIT : I appreciate all the answers... and I don't think they are really getting at the problem. 編輯 :我很感謝所有的答案......我認爲他們並沒有真正解決問題。 Some of them are about styling and don't seem to relate... and others just mention javascript_include_tag ... which I know exists (obviously...) but it would appear that the Rails 3.1 way going forward is to wrap up all of your JavaScript into 1 file rather than loading individual JavaScript at the bottom of each page. 其中一些是關於樣式的,似乎沒有關聯...而其他人只是提到javascript_include_tag ...我知道存在(顯然......)但是看起來Rails 3.1的方式將會結束所有將您的JavaScript分成1個文件,而不是在每個頁面底部加載單獨的JavaScript。

The best solution I can come up with is to wrap certain features in div tags with id s or class es. 我能拿出最好的解決辦法是包裝在某些功能div標籤與id S或class上課。 In the JavaScript code, you just check if the id or class is on the page, and if it is, you run the JavaScript code that is associated with it. 在JavaScript代碼中,您只需檢查頁面上是否包含idclass ,如果是,則運行與其關聯的JavaScript代碼。 This way if the dynamic element is not on the page, the JavaScript code doesn't run - even though it's been included in the massive application.js file packaged by Sprockets. 這樣,如果動態元素不在頁面上,則JavaScript代碼不會運行 - 即使它已包含在由Sprockets打包的大量application.js文件中。

My above solution has the benefit that if a search box is included on 8 of the 100 pages, it will run on only those 8 pages. 我的上述解決方案的好處是,如果在100個頁面中的8個頁面中包含搜索框,則它將僅在這8個頁面上運行。 You also won't have to include the same code on 8 of the pages on the site. 您也不必在網站的8個頁面上包含相同的代碼。 In fact, you'll never have to include manual script tags on your site anywhere ever again. 實際上,您永遠不必在任何地方再次在您的網站上包含手動腳本標記。

I think this is the actual answer to my question. 我認爲這是我問題的實際答案。


#1樓

參考:https://stackoom.com/question/PsWj/使用Rails-您在哪裏放置-特定於頁面-的JavaScript代碼


#2樓

You can add this line in your layout file (eg application.html.erb) to automatically load the controller specific javascript file (the one that was created when you generated the controller): 您可以在佈局文件中添加此行(例如application.html.erb)以自動加載控制器特定的javascript文件(生成控制器時創建的文件):

<%= javascript_include_tag params[:controller] %>

You also could add a line to automatically load a script file in a per-action basis. 您還可以添加一行以自動加載腳本文件。

<%= javascript_include_tag params[:controller] + "/" + params[:action] %>

Just put your page scripts into a subdirectoriy named after the controller name. 只需將頁面腳本放入以控制器名稱命名的子目錄中即可。 In these files you could include other scripts using =require. 在這些文件中,您可以使用= require包含其他腳本。 It would be nice to create a helper to include the file only if it exists, to avoid a 404 fail in the browser. 如果文件存在,創建一個幫助程序來包含文件會很好,以避免瀏覽器中的404失敗。


#3樓

I have another solution, which although primitive works fine for me and doesn't need any fancy selective loading strategies. 我有另一種解決方案,雖然原始對我來說很好,並且不需要任何花哨的選擇性加載策略。 Put in your nornal document ready function, but then test the current windows location to see if it is the page your javascript is intended for: 放入你的nornal文檔就緒函數,然後測試當前的windows位置,看看它是你的javascript用於的頁面:

$(document).ready(function() {
   if(window.location.pathname.indexOf('/yourpage') != -1) {
          // the javascript you want to execute
   }
}

This still allows all the js to be loaded by rails 3.x in one small package, but does not generate much overhead or any conflicts with pages for which the js isn't intended. 這仍然允許所有js由rails 3.x在一個小包中加載,但是不會產生很多開銷或與js不打算的頁面有任何衝突。


#4樓

I agree with your answer, to check if that selector is there, use: 我同意你的回答,檢查選擇器是否在那裏,使用:

if ($(selector).length) {
    // Put the function that does not need to be executed every page
}

(didn't see anyone add the actual solution) (沒有看到有人添加實際的解決方案)


#5樓

您還可以將js分組到文件夾中,並繼續使用資產管道根據頁面選擇性地加載您的JavaScript


#6樓

This has been answered and accepted long ago, but I came up with my own solution based on some of these answers and my experience with Rails 3+. 這已經很久以前得到了回答和接受,但我根據其中的一些答案以及我對Rails 3+的經驗提出了自己的解決方案。

The asset pipeline is sweet. 資產管道很好。 Use it. 用它。

First, in your application.js file, remove //= require_tree. 首先,在application.js文件中,刪除//= require_tree.

Then in your application_controller.rb create a helper method: 然後在application_controller.rb創建一個輔助方法:

helper_method :javascript_include_view_js //Or something similar

def javascript_include_view_js
    if FileTest.exists? "app/assets/javascripts/"+params[:controller]+"/"+params[:action]+".js.erb"
        return '<script src="/assets/'+params[:controller]+'/'+params[:action]+'.js.erb" type="text/javascript"></script>'
    end
end

Then in your application.html.erb layout file, add your new helper among the existing javascript includes, prefixed with the raw helper: 然後在您的application.html.erb佈局文件中,在現有的javascript包含中添加新的幫助application.html.erb ,前綴爲raw幫助程序:

<head>
    <title>Your Application</title>
    <%= stylesheet_link_tag "application", :media => "all" %>
    <%= javascript_include_tag "application" %>
    <%= raw javascript_include_view_js %>
</head>

Voila, now you can easily create view-specific javascript using the same file structure you use everywhere else in rails. 瞧,現在你可以使用你在rails中的其他地方使用的相同文件結構輕鬆創建特定於視圖的javascript。 Simply stick your files in app/assets/:namespace/:controller/action.js.erb ! 只需將文件粘貼到app/assets/:namespace/:controller/action.js.erb

Hope that helps someone else! 希望能幫助別人!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章