I have two code snippets and the following questions:

  1. Which uses the best practice and why?
  2. Which one is good for performance?

Code 1

jQuery( function( $ ) {

    // Responsive video
    var $area = $( "#sidebar" );
    $area.fitVids();

    // Image gallery
    var $slider = $( ".owl-carousel" );
    $slider.owlCarousel();

});

Code 2

// Global jQuery variable
var $ = jQuery;

/**
 * Responsive video
 */
var fitvidsInit = function() {
    var $area = $( "#sidebar" );
    $area.fitVids();
};

/**
 * Slides
 */
var sliderInit = function() {
    var $slider = $( ".owl-carousel" );
    $slider.owlCarousel();
};

/**
 * Execute code
 */
$( function() {
    fitvidsInit();
    sliderInit();
} )

I also have to defined the variable $ because this is in WordPress.

share|improve this question
    
You've already received an answer based on two code snippets. Please don't modify them and add a new one. – Jamal Nov 7 '15 at 4:59
    
Oh, why? Should I create new question? Because the third code are different. – Satrya Nov 7 '15 at 5:00
    
I suppose, or you could wait for further reviews. This one was up for just a day already. – Jamal Nov 7 '15 at 5:02
    
Oh ok, thank you for the explanation Jamal. – Satrya Nov 7 '15 at 5:27
up vote 1 down vote accepted

Any performance difference would be too small to measure.

Code 2 pollutes the global namespace with three variables: $, fitvidsInit, and sliderInit. Therefore, Code 1 is better. I suggest eliminating $area and $slider as well:

jQuery( function( $ ) {

    // Responsive video
    $( "#sidebar" ).fitVids();

    // Image gallery
    $( ".owl-carousel" ).owlCarousel();

});
share|improve this answer
    
Actually I've more code to see but I'll accept your answer. Your explanation are make sense for me – Satrya Nov 7 '15 at 8:15

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.