JavaScript/jQuery Best Practices


  1. Use vanilla JS instead jQuery where possible
  2. Utilize Eslint
    available in all popular editors and IDE.

  3. Great resource for JS learning javascript.info

  4. ExecWhenReadyPoller

    • Be sure to use execWhenReadyPoller()
      u.execWhenReadyPoller(function(){
          //your code
      },u.poller('jquery'));
      

You could to use execWhenReadyPoller() for libraries like:

  • jQuery (important)
  • jqueryUI
  • callbox
  • fancybox
  • gplus
  • jCarousel
  • mustache
  • raty
  • slick
  • staticRow
  • stickyTableHeaders
  • tableSorter
  • and more...

For any other library use:

   u.execWhenReady(function(){
          //your code
   },'jQuery.fn.slick');
  1. Use === Instead of == When Possible
  2. Reduce Globals:

    //instead
       var productName = 'Casumo';
       var score = 9.8;
       function doSomething() {...}
    
    //use
    var casumoPartner = {
       name : 'Casumo',
       score : 9.8,
       doSomething : function() {...}
    }
    
  3. Always comment Your Code

  4. Use map/filter/reduce/every/forEach (Array.prototype) instead for statment where possible

  5. Avoiding loops for..in

  6. Caching DOM element inside of a variable

    //instead
    $(".class-name").attr("title", text);
    $(".class-name").each(...)
    //use
    var $query = $(".class-name");
    $query.attr("title", text);
    $query.each(...)
    
  7. Omitting Nested Elements

    //instead
    $('ul .el')...;
    $('#featuresList > li:odd ')
    
    //use
    $('ul').find('.el')...;
    $('#featuresList').children('li:odd')
    
  8. Chain When Possible

    //instead
    $('body').hide();
    $('body').append('<span>Hello</span>');
    $('body').show();
    
    //use
    $('body')
        .hide()
        .append('<span>Hello</span>')
        .show();
    
  9. Code Safe

    • Method 1 Passing jQuery
      (function($) {
       // use refer $ to jQuery
      })(jQuery);
      
    • Method 2 NoConflict
      var _ = jQuery.noConflict();
      // instead of $, we use _ 
      _('.chart-table').clearQueue();
      
  10. Use this function for event tracking

    // u.trackEvent.toString()
    function trackEvent(eventArr) {
    var g = window._gaq || (window._gaq = []);
    g.push(eventArr);
    if (!(window.attachEvent && !_d.createEvent)) {
        var trackingObj = {
            detail: {
                category: eventArr[0],
                action: eventArr[1],
                opt_label: eventArr[2],
                opt_value: eventArr[2],
                opt_noninteraction: eventArr[4]
            }
        };
        var evt = _d.createEvent("Event");
        evt.initEvent("trackEvent", true, false);
        evt.detail = eventArr;
        _d.dispatchEvent(evt)
    }
    }
    

results matching ""

    No results matching ""