我有這樣的代碼:
$(document).ready(function() {
$('.accessLink')
.bind('click', accessLinkClick);
$('#logoutLink')
.click(function (e) {
window.location = $(this).attr('data-href')
});
});
功能爲我的網站的每個部分分成若干小文件和當這個網站被部署時,這些網站將會被整合並加入進來。
這些小文件中的每一個最多可以等待$(document).ready。任何人都可以告訴我這樣做是否有很多開銷。分割我的代碼爲功能區域,意味着該代碼看起來很容易維護,但我只是想知道現在的開銷,我使用jQuery 1.8.1
更新:
基礎上的答案,我開始像這樣的代碼:
$(document).ready(function() {
accessButtons(); // login, register, logout
layoutButtons();
themeButtons(); // theme switcher, sidebar, print page
});
每個函數,則編碼爲:
function accessButtons() {
$('.accessLink')
.bind('click', accessLinkClick);
$('#logoutLink')
.click(function (e) {
window.location = $(this).attr('data-href')
});
};
會有一個(非常)小的性能開銷,但是當你測試你的網頁時你可能不會注意到問題嗎?如果它簡化了維護,那麼這足以證明是正確的? – nnnnnn
開銷包含多次調用'$()。ready'(而不是一個/幾個)並調用多個回調(而不是一個/幾個)。但是否對您的網站/應用程序的性能有任何影響是另一個問題。很可能不會。 –
Check out http://stackoverflow.com/questions/1327756/can-you-have-multiple-document-readyfunction-sections或http://stackoverflow.com/questions/1148241/jquery-is-it-bad-to -have-multiple-document-readyfunction http://stackoverflow.com/questions/5263385/jquery-multiple-document-ready –