jQuery Tip && Trick






                                                                                      @ unclelongmao

Prrfix


  • Syntax
  • Data Storage
  • Optimization
  • miscellaneous

syntax

  • Writing your own selectors   

$.extend($.expr[":"], {
    over100pixels: function (e) {
        return $(e).height() > 100
    }
}) 

systax

  • Give your Selectors a Context
  •  // grammar style // $(expression, context) $('.class', '#class-container')    .css ('color', '#f00');

DATA STORAGE


  • jQuery Data()
    • bind data to dom  without modify the dom
    •  var $body = $("body"); $body.data("isWebTag",true)

performance

  • Var Caching 
    • Cache selected elements
    • Use Hungarian Notation
    • Never forget using cache  inside a loop
  • var $body = $("body");$body.css("width",900)$body.on("click","img",function(){})

Performance


  • Avoid Universal Selectors
  •  // bad
    
    $('.container > *'); 
    
    // better
    
    $('.container').children();

Performance


  • Optimize Selectors
  •  // bad
    
    $('div#myid'); 
    $('div#footer a.myLink');
    
    // better
    $('#myid');
    $('#footer .myLink');

miscellaneous

  • Use Var Chaining (Single Var Pattern)
  • var 
      $first = $('#first'),
      $second = $('#second'),
      value = $first.val(),
      k = 3,
      cookiestring = 'SOMECOOKIESPLEASE',
      i,
      j,
      myArray = {};

miscellaneous

  • Use Chaining
  • var $body =  $(body);$body   .css("width",100)   .on("click","img",function(){console.log("img clicked")})         

miscellaneous

  • Prefer Short-circuiting
  • var test1 = false,test2; if(test1){  test2 = "yes"}else{  test2 = "no"}//new wayvar test1 = false,test2; 
    test2 = test1 ? "yes" : "no"test2 = test1 && "yes" || "no"

miscellaneous

  • Try to Use the Latest Version
    • faster speed 
    • no more support for ie8- in the 2.0  

jQuery Tip && Trick

By Uncle Longmao

jQuery Tip && Trick

introduce some slick jquery using tip, enjoy !

  • 751