23
est Code Practices & Tips and Trick

Javascript and Jquery Best practices

Embed Size (px)

Citation preview

Page 1: Javascript and Jquery Best practices

Best Code Practices & Tips and Tricks

Page 2: Javascript and Jquery Best practices

What is Javascript & jQuery

JavaScript jQueryDevelopers need to handle by writing their own Javascript code.

Query is a multi-browser JavaScript library designed to simplify the client-side scripting of HTML.

If you use JavaScript, you need to write you own scripting which may take time.

If you use Jquery, you need not to write much scripting which already exists in JQuery.

JavaScript is a language. Example: JQuery like a foriegn language which is already built by Javascript which is unknown to you what kind of JS is written there, you are just using it.

JQuery is a framework built with JavaScript to help JavaScript programmers who are doing common web tasks. Example: But if you goto a country where it is spoken, a guide can still help you along, making your journey easier. jQuery is one of many frameworks which provide help in areas that can be frustrating when writing plain JavaScript

Page 3: Javascript and Jquery Best practices

• Don’t forget var keyword when assigning a variable’s value for the first time.Example: name='Javascript'; // Bad Practice

var name='JavaScript'; // // GoodPractice

• Use === instead of ==Example: if(name=='Javascript') // Bad Practice

if(name==='Javascript') // Good Practice

• Use Semicolons for line termination.Example:

firstName = 'Sultan' // Bad Practices lastName = 'Khan' // Bad Practices

firstName = 'Sultan'; // Good Practices lastName = 'Khan'; // Good Practices

JavaScript Best Practices

Page 4: Javascript and Jquery Best practices

•Avoid these JavaScript’s Keywords When Creating Custom Identifiers

break ,case, catch, continue, default, delete, do, else, finally, for, function, if, in, instanceof, new, return, switch, this, throw, try, typeof, var, void, while, With

•Avoid the use of eval() or the Function constructor

Use of eval or the Function constructor are expensive operations as each time they are called script engine must convert source code to executable code.

var func1 = new Function(functionCode);var func2 = eval(functionCode)

•Don’t Change a Variable’s Type After Initial Declaration

var my_variable = "This is a String";my_variable = 50;

Page 5: Javascript and Jquery Best practices

• Make Multi-Line Comments Readable, But Simple/* * This is a multi-line comment ... * cont'd... * cont'd... * cont'd... * cont'd... */

• Verify the argument before passing it to isFinite()isFinite(0/0) ; // false isFinite("foo"); // false isFinite("10"); // true isFinite(10); // true isFinite(undefined); // false isFinite(); // false

Page 6: Javascript and Jquery Best practices

• Avoid using for-in loop for arraysvar sum = 0; for (var i in arrayNumbers) { sum += arrayNumbers[i]; }var sum = 0; for (var i = 0, len = arrayNumbers.length; i < len; i++) { sum += arrayNumbers[i]; }

• Pass functions, not strings, to setTimeout()  and setInterval()

setInterval('doSomethingPeriodically()', 1000); setTimeout('doSomethingAfterFiveSeconds()', 5000);

setInterval(doSomethingPeriodically, 1000); setTimeout(doSomethingAfterFiveSeconds, 5000);

Page 7: Javascript and Jquery Best practices

• Use a switch/case statement instead of a series of if/elseUsing switch/case is faster when there are more than 2 cases, and it is more elegant (better organized code). Avoid using it when you have more than

10 cases.

• Avoid using try-catch-finally inside a loop

ar object = ['foo', 'bar'], i; for (i = 0, len = object.length; i <len; i++) { try { // do something that throws an exception } catch (e) { // handle exception } }

var object = ['foo', 'bar'], i; try { for (i = 0, len = object.length; i <len; i++) { // do something that throws an exception } } catch (e) { // handle exception }

Page 8: Javascript and Jquery Best practices

• Instead of reading the length of an array at every iteration, you should get it only once.

for (var i = 0; i < value.length; i += 1) { console.log(value[i]);}

for (var i = 0, iCnt = haystack.length; i < iCnt; i += 1) { console.log(haystack[i]);}

• You can concatenate strings in many ways, but most efficient is Array.join()

var store = {'lemon': 'yellow', 'cherry': 'red'} var str = "Lemons are " + store.lemon + ", tomatos are" + store.cherry;

var str = ["Lemons are ", store.lemon, ", tomatos are", store.cherry].join("");

Page 9: Javascript and Jquery Best practices

• Use a variable initialized with a Function Expression to define a function within a block.

if (x) { function foo() {}}

if (x) { var foo = function() {};}

• No reason to use wrapper objects for primitive types, plus they're dangerous.

var x = new Boolean(false); if (x) { alert('hi'); // Shows 'hi'.}

var x = Boolean(0);if (x) { alert('hi'); // This will never be alerted.}

Page 10: Javascript and Jquery Best practices

• Always Use Closure function foo(element, a, b) { element.onclick = function() { /* uses a and b */ };}

function foo(element, a, b) { element.onclick = bar(a, b);}

function bar(a, b) { return function() { /* uses a and b */ };}• Do not use Multiline string literalsvar myString = 'A rather long string of English text, an error message \ actually that just keeps going and going -- an error \ message to make the Energizer ';

var myString = 'A rather long string of English text, an error message ' + 'actually that just keeps going and going -- an error ' + 'message to make the

Energizer';

Page 11: Javascript and Jquery Best practices

• For consistency single-quotes (') are preferred to double-quotes ("). This is helpful when creating strings that include HTML:

var msg = 'This is some HTML';

Don’t forget to use a code beautifier when coding. Use JSLint and minification (JSMin, for example) before going live.

Page 12: Javascript and Jquery Best practices

Best Practices

Page 13: Javascript and Jquery Best practices

• Always load your jQuery framework from CDN<script type="text/javascript" src="/js/jquery.js"></script>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">

</script>

• Always Use Shorthand for $(document).ready()$(document).ready(function() {    ....});

$(function() {});

Page 14: Javascript and Jquery Best practices

• Load jQuery locally when CDN fails<script type="text/javascript"

src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>

<script type="text/javascript">if (typeof jQuery == 'undefined'){ document.write('<script src="/js/jqeury.js"></script>');}</script>

• Always try to use ID as selector$("#elmID");

• Use class selector with tags$(".myCSSClass");

$(“div .myCSSClass”)

Page 15: Javascript and Jquery Best practices

• Keep your selector simple, don't make it complex

$("body .main p#myID em");

$("p#myID em");

• Don't use your selector repeatedly.$("#myID").css("color", "red");$("#myID").css("font", "Arial");$("#myID").text("Error occurred!");

$("p").css({ "color": "red", "font": "Arial"}).text("Error occurred!");

Page 16: Javascript and Jquery Best practices

• when you are comparing empty elements try to follow this

$(document).ready(function() { if ($('#dvText').html().trim()) { alert('Proceed as element is not empty.'); } else { alert('Element is empty'); }});

• Avoid jQuery.Post(), use jQuery.ajax()$.post( url, [data], [callback], [type] )

$.ajax({url: "", success: function(result){},error:function(result){});

Page 17: Javascript and Jquery Best practices

• Cache jQuery Objects$('#traffic_light input.on).bind('click', function(){...});$('#traffic_light input.on).css('border', '3px dashed yellow');$('#traffic_light input.on).css('background-color', 'orange');$('#traffic_light input.on).fadeIn('slow');

var $active_light = $('#traffic_light input.on');$active_light.bind('click', function(){...});$active_light.css('border', '3px dashed yellow');$active_light.css('background-color', 'orange');$active_light.fadeIn('slow');

• Classes are GreatUse CSS classes whenever possible instead of inline CSS. $("element").css({"color":"red","font-size:"20px"}) $("element").addClass("pstyle");

Page 18: Javascript and Jquery Best practices

• jQuery's Chaining FeatureChaining is a great feature in jQuery that allows you to chain method calls. Here is an Example:$

('sampleElement').removeClass('classToBeRemoved').addClass('classToBeAdded');

• Always use data method and avoid storing data inside the DOM

$('#selector').attr('alt', 'your description.....');$('#selector').data('alt', 'your description.....');

• Use find() rather than context

var divs = $('.testdiv', '#pageBody'); var divs = $('#pageBody').find('.testdiv'); var divs = $('#pageBody .testdiv');

Page 19: Javascript and Jquery Best practices

• Write your own selectors$.extend($.expr[':'], {

abovethefold: function(el) {return $(el).offset().top < $(window).scrollTop() + $

(window).height();}

});var nonVisibleElements = $('div:abovethefold'); // Select the elements

• Store jQuery results for later

App.hiddenDivs = $('div.hidden');// later in your application:App.hiddenDivs.find('span');

Page 20: Javascript and Jquery Best practices

• Benchmark Your jQuery CodeAlways benchmark your code and see which query is slower to replace it// Shortcut to log data to the Firebug console$.l($('div'));// Get the UNIX timestamp$.time();// Log the execution time of a JS block to Firebug$.lt();$('div');$.lt();// Run a block of code in a for loop to test the execution time$.bm("var divs = $('.testdiv', '#pageBody');"); // 2353 on Firebug

• best way to Using $this keyword

$('li').each(function() { $(this).on('click', function() { $(this).addClass('active'); });});

Page 21: Javascript and Jquery Best practices

$('li').each(function() { var $this = $(this); $this.on('click', function() { $this.addClass('active'); });});

• Avoid the universal selectors

// Slow$('div.container > *');

// Faster$('.container').children();

Page 22: Javascript and Jquery Best practices

• Using filtering methods instead of pseudo selectors$('.item:first')

$('.item').eq(0)

• Don't put all parameters in Ajax URL$.ajax({ url: '/remote/url?param1=value1&param2=value2...'}});

$.ajax({ url: '/remote/url', data: { param1: 'value1', param2: 'value2' }});

Page 23: Javascript and Jquery Best practices

• References

• http://tutorialzine.com/• http://viralpatel.net/blogs/category/javascript/• https://learn.jquery.com/• http://www.sitepoint.com/javascript/jquery/