1
\$\begingroup\$

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.

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Nov 6, 2015 at 6:02
\$\endgroup\$
3
  • \$\begingroup\$ You've already received an answer based on two code snippets. Please don't modify them and add a new one. \$\endgroup\$ Commented Nov 7, 2015 at 4:59
  • \$\begingroup\$ Oh, why? Should I create new question? Because the third code are different. \$\endgroup\$ Commented Nov 7, 2015 at 5:00
  • \$\begingroup\$ I suppose, or you could wait for further reviews. This one was up for just a day already. \$\endgroup\$ Commented Nov 7, 2015 at 5:02

1 Answer 1

1
\$\begingroup\$

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();
});
answered Nov 6, 2015 at 6:53
\$\endgroup\$
1
  • \$\begingroup\$ Actually I've more code to see but I'll accept your answer. Your explanation are make sense for me \$\endgroup\$ Commented Nov 7, 2015 at 8:15

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.