我的其他程序員,我失去了我的想法。我關注了JS性能方面的許多書籍,並且他們都在說,最好是將DOM對象緩存以備將來參考和管理,而不是創建新的Jquery對象。這聽起來很合理。 但現在我的信仰在顫抖。我試圖在我的公司開發代碼約定,我正想從一個性能角度來解決這個問題。 我有一段代碼如下:原生Jquery選擇器VS緩存object.find()
$("#registratorType").attr("readonly", "readonly");
$("#registratorType").attr("size", "25");
$("#id").attr("readonly", "readonly");
$("#id").attr("size", "25");
$("#serial").attr("readonly", "readonly");
$("#serial").attr("size", "25");
$("#duration").attr("size", "25");
$("#stoppingDuration").attr("size", "25");
$("#speeddata").removeAttr("disabled");
它不是整個事情,但我認爲,你已經有了這個想法。我將獲得所有這些表單並將其包裝在緩存的參考中。
var $form = $('#vehicleProfile');
$form.find("#registratorType").attr("readonly", "readonly");
$form.find("#registratorType").attr("size", "25");
$form.find("#id").attr("readonly", "readonly");
$form.find("#id").attr("size", "25");
$form.find("#serial").attr("readonly", "readonly");
$form.find("#serial").attr("size", "25");
$form.find("#duration").attr("size", "25");
$form.find("#stoppingDuration").attr("size", "25");
$form.find("#speeddata").removeAttr("disabled");
我已經測試了最新的chrome中的性能,並且感到震驚!我的方法失敗了3-4次。我的意思是我的功能運行在42毫秒,而老的是12-14毫秒。 對我的方法有沒有真正的價值?我的方法是反模式嗎?請幫幫我!
這不是「緩存參考」的含義。 – Bergi
我認爲在'find()'中使用ID選擇器是無用的,你應該做的就像var'$ registratorType = $('#registratorType'); [']' –
緩存_finds_ like'var registratorType = $(「#registratorType」);'然後使用'registratorType.attr()'作爲'registratorType'變量是一個jQuery對象 – andyb