JavaScript/jQuery Best Practices
- Use vanilla JS instead jQuery where possible
Utilize Eslint
available in all popular editors and IDE.Great resource for JS learning javascript.info
ExecWhenReadyPoller
- Be sure to use execWhenReadyPoller()
u.execWhenReadyPoller(function(){ //your code },u.poller('jquery'));
- Be sure to use execWhenReadyPoller()
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');
- Use === Instead of == When Possible
Reduce Globals:
//instead var productName = 'Casumo'; var score = 9.8; function doSomething() {...} //use var casumoPartner = { name : 'Casumo', score : 9.8, doSomething : function() {...} }
Always comment Your Code
Use
map/filter/reduce/every/forEach (Array.prototype)
insteadfor
statment where possibleAvoiding loops
for..in
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(...)
Omitting Nested Elements
//instead $('ul .el')...; $('#featuresList > li:odd ') //use $('ul').find('.el')...; $('#featuresList').children('li:odd')
Chain When Possible
//instead $('body').hide(); $('body').append('<span>Hello</span>'); $('body').show(); //use $('body') .hide() .append('<span>Hello</span>') .show();
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();
- Method 1 Passing jQuery
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) } }