Increase jQuery performance

จาก WikiBall

การปรับปรุง เมื่อ 07:36, 9 กรกฎาคม 2552 โดย Spnball (พูดคุย | เรื่องที่เขียน)
(ต่าง) ←รุ่นก่อนหน้า | รุ่นปัจจุบัน (ต่าง) | รุ่นถัดไป→ (ต่าง)
ข้ามไปที่: นำทาง, ค้นหา

เนื้อหา

ใช้เวอร์ชั่นใหม่สุด

แน่นอนเสียเหลือเกินว่าของใหม่ย่อมดีกว่าของเก่า ดังนั้นเราจึงควรใช้ jQuery ในเวอร์ชั่นที่ใหม่กว่า

<!-- get the API with a simple script tag -->  
 <script type="text/javascript" src="<a href="http://www.google.com/jsapi%22%3E%3C/script">http://www.google.com/jsapi"></script</a>>  
 <script type="text/javascript">  
     /* and load minified jQuery v1.3.2 this way */  
     google.load ("jquery", "1.3.2", {uncompressed: false});  

     google.setOnLoadCallback (onLoad);  
 </script>

ใช้ For แทน Each

รวมสคริปซะ

รวมสคริปของทุกเพจไว้ด้วยกัน เพื่อที่จะให้บราวเซอร์โหลดแค่ครั้งเดียว

ใช้ ID แทน Class

ในการใช้ selecter ของ jQuery ควรจะใช้เลือกโดย ID แทนการเลือกด้วย class เช่น $('#demo') แทนการใช้ $('.example') ดังนั้นเราจึงควรเขียน HTML ใช้สนับสนุนการใช้งานในส่วนนี้ด้วย หรือถ้าจำเป็นต้องใช้ class จริงๆ ควรทำการสโคปการค้นหาให้เล็กลงเช่น $('.class', '#class-container')
$(expression, context)  
  • เก็บไว้ในตัวแปร

    อย่าทำการ select หลายครั้งที่เหมือนกัน เพราะจะทำให้เปลืองโหลดขณะทำการ select ดังนั้นเราควรที่จะเก็บใส่ตัวแปรของเราซะ
    $('#demo').html ('What's up');
    $('#demo').css ('color', '#444444'); 
    $('#demo').addclass ('fulltext');
    

    ควรใช้เป็น

    var demo = $('#demo');
    demo.html ('What's up');
    demo.css ('color', '#444444'); 
    demo.addclass ('fulltext');

    หรือ

     $('#demo').css ('color', '#444444').addclass ('fulltext');
    

    หลีกเลี่ยงการใช้ DOM Manipulation

    หลีกเลี่ยงการใช้ function เกี่ยวกับการทำ DOM ใหม่ append(), after(),prepend() โดยการใช้ html() แทน

    ใส่ return false ด้วย

    Function ที่ไม่มีการ return ใดๆ กลับมาเลย ควรเพิ่ม return false ด้วย

    ใช้ join แทน concat

    ถ้าข้อความเป็น array ควรใช้ join แทนการใช้ array มาบวกกัน

    reference

    http://net.tutsplus.com/tutorials/javascript-ajax/10-ways-to-instantly-increase-your-jquery-performance/

  • เครื่องมือส่วนตัว