You are on page 1of 40

1. Guidelines and Best Practices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

1.1 CSS Guidelines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .


1.2 Good Reads and Links . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.3 High Performance JS tips . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.4 HTML Guidelines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.5 Javascript Guidelines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.5.1 HowTo detect old IE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.5.2 JavaScript Commenting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.5.3 JavaScript Style . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.5.4 Object Constructor new Object() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.5.5 Omit the "Var" Keyword and Use Commas Instead . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.5.6 page_params Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.5.7 Understandability . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.5.8 Using class names for JS purposal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.6 jQuery best practices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.7 Load Files via OCS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.8 SVN Guidelines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

2
3
9
10
10
12
12
13
14
24
26
27
28
29
31
34
40

Guidelines and Best Practices


General
Coding standards specify a common format for the source code and comments. This allows developers to easily
share code and , and the ideas expressed within the code and comments, between each other. Having a standard
creates consistency and understanding between the developers.

DOCTYPE
The absence of a DOCTYPE is a crime punishable by death. You may have relied on the following DOCTYPE in the
past, but it's important to know that this is now being superseded by a leaner and meaner snippet.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0


Transitional//EN"
"http://w3.org/TR/xhtml1/DTD/xhtml1-transitiona
l.dtd">
Ideally, the HTML5 DOCTYPE should be used. It's supported in all modern browsers, and throws IE6 and IE7 into
standards mode. Source.

<!DOCTYPE html>
Use Tables for Tabular Data Only
Tables should only ever be used for the presentation of tabular data. The only exception is when composing HTML
email, in which a table is almost the only thing supported by soul crushing email clients.
For accessibility, table headers should always be presented using <th> elements. Remember to also set cellpad
ding,cellspacing and border values to 0 as these are more consistently controlled by CSS.

Error Handler function


Error Handler Function

var errorHandler
try{
console.error(
console.error(
console.error(
}catch( e ){};
};

= function( msg ){
"=======ERROR=======" );
msg );
"===================" );

Indentation
Use tabs, either way make sure that your entire project is using it. Use tabs ( 4 spaces size ) for all programming

languages HTML, CSS and Javascript.


Click on the image below:

CSS Guidelines
CSS Guidelines
Commenting
CSSDOC is a commenting convention much like Java Doc and PHP Doc. It provides a standard way for developers
to tag parts of a stylesheet with important meta information. Eventually it may be used to provide an enhanced
interface in your favorite IDE. Although it is still in the draft phase, CSSDOC is a great way to clean up your
stylesheets.

Syntax
This is the basic block in which all comments will be placed. It has a very specific markup. The opening line has one
forward slash followed by two asterisks. Each comment line thereafter should start with a single space an asterisk
and one more space. Finally to end the block use a single space, one asterisk, and another forward slash.

/**
*
*/

A tag is a single at sign (@) followed by some text with no space. Most tags can be followed by a single space and
some descriptive text, as follows:
Using Tag

/**
* @tag This is a tag!
*/

Additionally, each block may contain several lines that do not have tags. These lines are typically reserved for a title

and long description:


Description

/**
* Descriptive Title
*
* Your long description would go here, before any of the tags.
*/

File comment
Most designers want to put a little title block at the top of their stylesheets. It will usually include information about
the author and creation date. There are a lot of tags, I have included the most common ones in the example below.
File Comment Format

/**
* Stylesheet title
*
* Your stylesheet description would go here.
*
* @project Name
* @version 1.0
* @author Name
* @copyright Year
* @license Type
*/

Section and Subsection Comment


You can mark a section in your file with @section and @subsection tags. You can title these areas but I typically
find myself dropping the title and just including the section name.
Section and Subsection

/**
* ------------------------* @section Section
* ------------------------*/

Bug/Workaround Comment

Its a sad but true fact that we have to use hacks to fix browser display issues. Fortunately CSSDOC provides a
great way to mark these sections of code.
Bug/Workaround comment

/**
* Why the fix is here
*
* @workaround or @bugfix
* @affected browser
* @valid yes or no
*/

The workaround/bugfix syntax is a little confusing to me. Here is the explanation from the draft:
Bugfix: Should remove CSS-Rendering Problems without having bothersome effects.
Workaround: Some browsers need a reduced rendering because they are full of errors. A Workaround works
around those Issues.

Other Useful Tags


@colordef: For notating colors. Follow it with a #color and a description of what it is used for.
@see: If you need to reference a website you can drop a link after this tag. Its nice to give attribution.
@todo: I use this one all the time. Whenever you need to remember what you have to do next you can use
this tag.

NAMING
ID and Class Naming

Use meaningful or generic ID and class names.


Instead of presentational or cryptic names, always use ID
and class names that reflect the purpose of the element in
question, or that are otherwise generic.
Names that are specific and reflect the purpose of the
element should be preferred as these are most
understandable and the least likely to change.
Generic names are simply a fallback for elements that have
no particular or no meaning different from their siblings.
They are typically needed as helpers.
Using functional or generic names reduces the probability

of unnecessary document or template changes.


Id and class naming

/* Not recommended: meaningless */


#yee-1901 {}
/* Not recommended: presentational */
.button-green {}
.clear {}

/* Recommended: specific */
#gallery {}
#login {}
.video {}
/* Recommended: generic */
.aux {}
.alt {}

ID and Class Name Style

Use ID and class names that are as short as possible but as


long as necessary.
Try to convey what an ID or class is about while being as brief as possible.
Using ID and class names this way contributes to acceptable levels of understandability and code efficiency.
Id and class name style

/* Not recommended */
#navigation {}
.atr {}
/* Recommended */
#nav {}
.author {}

Shorthand Properties
Use shorthand properties where possible.
CSS offers a variety of shorthand properties (like font) that should be used whenever possible, even in cases
where only one value is explicitly set.
Using shorthand properties is useful for code efficiency and understandability.

/* Not recommended */
border-top-style: none;
font-family: palatino, georgia, serif;
font-size: 100%;
line-height: 1.6;
padding-bottom: 2em;
padding-left: 1em;
padding-right: 1em;
padding-top: 0;
/* Recommended */
border-top: 0;
font: 100%/1.6 palatino, georgia, serif;
padding: 0 1em 2em;

/* Recommended */
background: #fff url(image.gif) no-repeat top left;
font: 1em/1.5em bold italic serif;
margin: 5px 10px;

CSS STYLE RULES


Use 3 characters hexadecimal notation, if possible
Use of 3 characters
.myClass {
color: #fff;
background-color: #000;
}

No units after 0 values (unless they are required)

.myClass {
bottom: 0;
font-size: 12px;
margin: 0;
padding: 3px 0;
}

Semicolon after every declaration

/** NOTE THE SEMICOLON AT THE END OF EVERY DECLARATION **/


.myClass {
bottom: 0;
margin: 0;
padding: 3px 0;
}

Separate CSS rules by a new line

#header {
display: block;
}
.logo {
display: block;
}

Put a space before the { in rules declaration & a space after : in property

#header {
display: block;
}

Avoid using !important

/**
* THIS SHOULD BE AVOIDED
*/
#header {
display: block !important;
}

Order
Alphabetize the properties inside each selector, If using LESS, put all mixins at the top.
For sublime user, there is a plugin called CSScomb that does the sorting for you

#header {
.radius(4px);
background: #000;
border: 1px solid #ccc;
color: #fff;
text-align: center;
}

Good Reads and Links


If You're A JavaScript Noob, Read These:
JavaScript: The Good Parts, by Douglas Crockford
The good news is, this book is very short. The bad news is, it's very dense and will likely require a lot of thinking and
re-reading. But The Good Parts is, in my mind, the definitive guide on how an engineer should approach JavaScript.
If you take nothing else aware from this article, please take away this: read The Good Parts.

Best Practices for Speeding Up Your Site, by the Yahoo! Developer Network
In particular, check out the JavaScript section. This is the best guideline for optimization I'm aware of.

Constructors considered mildly confusing, by Joost Diepenmaat


If you've ever been confused by how constructors and the prototype property work in JavaScript, this article does a
very detailed job of explaining how they work.

jQuery API
jQuery is essential for the modern JavaScript developer. Consult their API docs to learn all the library has to offer.

If You're A JavaScript Ninja, Read These:


The Surprisingly Elegant JavaScript Type Model, by Kannan Vijayan
JavaScript's type model is deceptively complicated, but this article does the best job I've ever seen of explaining it.

JavaScript Object vs Function experiment, by Steve Kwan


If you liked Kannan's article, you might like this. It's a really trippy demonstration of the relationship between the
Object and Function objects.

Partial Application in JavaScript, by Ben Alman


Currying and partial function application are important, but advanced, concepts within functional languages like
JavaScript. When you're ready to truly master these concepts, this article is one of the best

JavaScript constructor vs prototype experiment, by Steve Kwan


If you really want to understand constructor vs prototype, here's an in-depth example.

High Performance JS tips


Put all <script> tags at the bottom of the page
Group scripts together
Load scripts
Use litreral values and local variables
How to try-catch
***
Remember, pure JS code usually is much faster than any jQuery method.

/* this code is JS */
var i = 0,
j = a.length;
for (; i < j; i++) {
e = a[i];
}
/* this is jQuery, and it's 92% slower than JS */
$.each(a, function() { e = this; })

HTML Guidelines
Naming Classes and Id's
Avoid using dash "-" in classes or HTML id's use camelCase or underscore "_" instead.

<!--INSTEAD OF-->
<div id="my-div" class="grey-Button" data-listType="video">Click
me</div><!--/#my-div-->
<!--USE SOMETHING LIKE-->
<div id="myDiv" class="grey_Button" data-list_type="video">Click
me</div><!--/#myDiv-->

Avoid camelCase name when data attribute is used, the attribute name should be in lowercase and you can use
underscore if needed.

<!--INSTEAD OF-->
<div id="myDiv" class="grey_Button" data-listType="video">Click
me</div><!--/#myDiv-->

<!--USE SOMETHING LIKE-->


<div id="myDiv" class="grey_Button" data-list_type="video">Click
me</div><!--/#myDiv-->

For css class used by javascript, add js_ prefix followed by camel case words or use underscore, you can use that
class for CSS purposes as well.

<div id="myDiv" class="js_greyButton" data-listType="video">Click


me</div><!--/#myDiv-->

Quotation mark
Use double quotes all the time for HTML attribute values.
HTML Quotation Mark

<!--NOTE ALL THE ATTRIBUTES USE DOUBLE QUOTES AND THEY ARE ALL IN LOWERCASE-->
<div id="myDiv" class="js_greyButton" data-listType="video">Click
me</div><!--/#myDiv-->

COMMENTING CLOSING DIVS


In order to improve code readability and layout debug is a good practice to comment all the closing divs.

HTML

<!--COMMENTING CLOSING DIV ONLY CONTAINING ID-->


<div id='myDivSample'>
Amazing HTML code here
</div><!--#myDivSample-->
<!--COMMENTING CLOSING DIV ONLY CONTAINING CSS-->
<div class='myClass'>
Amazing HTML code here
</div><!--.myClass-->
<!--COMMENTING CLOSING DIV WITH BOTH CLASS AND ID-->
<div id='myDivSample' class='myClass'>
Amazing HTML code here
</div><!--.myDivSample-->

Multiline properties
In order to improve code readability in the case an HTML element has plenty of properties is a good practice to use
multiline propertys in HTML
Multiline HTML properties

<iframe
id="myId"
name="myName"
width="315"
height="300"
scrolling="no"
src="http://ss.phncdn.com/iframe-1.1.1.html#zone_id=90&amp;amp;site_id=13&amp;amp;c
ache=1410991481&amp;amp;c=HomePage&amp;amp;channel[Searched_Terms]=HomePage"
data-adzone="12345"></iframe>

Javascript Guidelines

Use semicolon after "use strict"


Put semicolon on the last method inside the objects.
HowTo detect old IE
HowTo detect old IE
JavaScript Commenting
JavaScript Style
Object Constructor new Object()

Omit the "Var" Keyword and Use Commas Instead


page_params Object
Understandability
Using class names for JS purposal

HowTo detect old IE without checking User Agent string


Checking old IE without User Agent String

<script>
var page_params = {
isOldIE : false
};
</script>
<!--[if lte IE 8 ]>
<script> page_params.isOldIE = true; </script>
<![endif]-->

HowTo detect old IE (only 7 bytes)


Checking old IE only 7 bytes

if( !+"\v1" ) // is IE
// returns NaN on IE 8 and less, and 1 in every other browser including IE 9->11

JavaScript Commenting
HowTo detect old IE
JavaScript Commenting
JavaScript Style
Object Constructor new Object()
Omit the "Var" Keyword and Use Commas Instead
page_params Object
Understandability
Using class names for JS purposal

Commenting
It is assumed that you will want to document things like: namespaces, classes, methods, method parameters, etc.
Comments should generally be placed immediately before the code being documented. It must start with a /** seq
uence or //

Simple Documentation

/** This is a description of the foo function. */


function foo(){
//statements here
}

Adding a description is simple, just type the description you want in the documentaton comment.
Special "documentation tags" can be used to give more information. For example, if the function is a constructor,
you can indicate this by adding a tag.
Documentation with tag to describe your code

/**
* Represents a video.
* @constructor
*/
function Video( title, user ){
//statements here
}

More tags can be used to add more information.


Adding more information with tags

/**
* Represents a video.
* @constructor
* @param {string} title - The title of the video.
* @param {string} user - The user of the video.
*/
function Video( title, user ){
//statements here
}

Source: Commenting guideline

JavaScript Style
HowTo detect old IE
JavaScript Commenting
JavaScript Style

Object Constructor new Object()


Omit the "Var" Keyword and Use Commas Instead
page_params Object
Understandability
Using class names for JS purposal

For loops
Try to declare the vars before running the for loop avoiding to check and declare vars during the loop
For Loop

//INSTEAD OF
var myArray = [ "cabeza", "tronco", "extremidades".... ];
for( var i=0; i<myArray.length; i++ ){
//DO SOMETHING AMAZING WITH myArray(i);
}
//DO
var myArray = [ "cabeza", "tronco", "extremidades".... ],
i = 0,
j = myArray.length;
for ( ; i<j; i++ ){
//DO SOMETHING AMAZING WITH myArray(i);
}

Always use braces & have them on the same line


Functions in JS

if( foo ){
alert( 'Hello world!' );
}

Avoid comparing true or false

Comparing TRUE or FALSE

if( foo ){ //true


//This is a good practice
}
if( !foo ){ //false
//This is a good practice
}
if( foo === true ){
//This works but we are trying to avoid this practice
}
if( foo === false){
//This works but we are trying to avoid this practice
}

Use shorthand, if possible


Shorthands

var element = ( type ) ? "video" : "photo";

Declare the vars before the loop


For Loop

var myArray = [ 'value 01', 'value 02', 'value 03', valueId ],


i = 0,
j = myArray.length;
for( ; i<j; i++ ){
console.log( myArray[i] );
}

Multiline conditions

Multiline statements

//this is good
if($(this).find("option:selected").val() == "Gender" ||
$(this).find("option:selected").val() == "Birth Year"){
//statements here
}

//this is better
if( $( this ).find( 'option:selected' ).val() === 'Gender' ||
$( this ).find( 'option:selected' ).val() === "Birth Year" &&
$( this ).find( 'option:selected' ).val() !== 'undefined' ){
//statements here
}

Beautiful Syntax
if / else / for / while / try always have spaces, braces and span multiple lines this encourages readability.

Parens, Braces, Linebreaks


var i = 0,
length = 100;
for( ; i<length; i++ ){
// statements
}
var prop;
for( prop in object ){
// statements
}
if( true ){
// statements
} else {
// statements
}
// Named Function Declaration
function foo( arg1, argN ){
// statements
}
// Usage
foo( arg1, argN );
// Named Function Declaration
function square( number ){
return number * number;
}
// Usage
square( 10 );

Use Correct <script> Tags


The LANGUAGE attribute is deprecated in the <script> tag. The proper way to create a javascript code block is:

Script Tag

<script type="text/javascript">
// code here
</script>
or
<script>
// code here
</script>
DO NOT use (some IDEs still generate it):
<script type="application/javascript">

Use {} Instead of new Object() and [] instead of new Array()


There are multiple ways to create objects in JavaScript. Perhaps the more traditional method is to use the "new"
constructor, like so:

//Good
var o = new Object();
o.name = 'Carlitos';
o.lastName = 'Way';
o.someFunction = function() {
console.log( this.name );
}
//Better
var o = {
'name': 'Carlitos',
'lastName' : 'Way',
'someFunction' : function() {
console.log( this.name );
}
};
//Note that if you simply want to create an empty object, {} will do the trick.
var o = {};

Array
//good
var a = new Array();
a[0] = 'Carlitos';
a[1] = 'Way';
//better
var a = [ 'Carlitos', 'Way' ];

Use JSON
When storing data structures as plain text or sending/retrieving data structures via Ajax, use JSON instead of XML
when possible. JSON (JavaScript Object Notation) is a more compact and efficient data format, and is
language-neutral.

var myJson = {};


myJson.name = 'Carlitos';
myJson.lastName = 'Way';

Avoid 'eval'
The eval() function in javascript is a way to run arbitrary code at run-time. In almost all cases, eval should never be
used. If it exists in your page, there is almost always a more correct way to accomplish what you are doing. For
example, eval is often used by programmers who do not know about using Square Bracket Notation.
The rule is, "Eval is evil."

Javascript in the footer


Place Scripts at the Bottom of Your Page after the </body> closing tag
Remember -- the primary goal is to make the page load as quickly as possible for the user. When loading a script,
the browser can't continue on until the entire file has been loaded. Thus, the user will have to wait longer before
noticing any progress.
If you have JS files whose only purpose is to add functionality -- for example, after a button is clicked -- go ahead
and place those files at the bottom, just before the closing body tag. This is absolutely a best practice.

<p>And now you know my favorite kinds of corn. </p>


</body>
<script type="text/javascript" src="path/to/file.js"></script>
<script type="text/javascript" src="path/to/anotherFile.js"></script>
<script type="text/javascript">
var amazingVar = "amazing string";
... AMAZING CODE NEEDED HERE ( IF NOT POSSIBLE TO PUT IN AN EXTERNAL FILE ) ...
</script>
</html>

No inline JavaScript
Avoid inline JavaScript as much as you can, is better to load the scripts in external files, however, if you need to get
values from back end in the page please place the script at the end of the template.

Avoiding inline javaScript

<div id="footer-copyright">
<span id="copyright">Copyright &copy; 2007-2014 Tube8.com, All Rights Reserved:
</span>
<div class="ascapContainer"></div>
<div class="rtaLogoContainer"><a
href="http://www.tube8.com/info.html#rta"></a></div>
</div><!--/footer-copyright-->
<script type="text/javascript">
/**
* HUBTRAFFIC SCRIPT TE-5017
**/
function mg_playerEvent(onSeek) {
//statements here
}
/* =========================================== */
/* FUNCTION TO CHECK IF THE USER IS LOGGUED IN */
/* =========================================== */
function downloadVideo() {
//statements here
}
/* ========================================= */
/* RELATED VIDEO BUTTONS NEXT AND PREV LOGIC */
/* ========================================= */
function updateRelated (page) {
//statements here
}
</script>
<!--HTML CODE HERE-->
<div id="footer-copyright2">
<span id="copyright2">Copyright &copy; 2007-2014 Tube8.com, All Rights Reserved:
</span>
<div class="ascapContainer"></div>
<div class="rtaLogoContainer"><a
href="http://www.tube8.com/info.html#rta"></a></div>
</div><!--/footer-copyright2-->

Always, Always Use Semicolons


The title is very descriptive, in order to minify the code properly is a good practice to use ALWAYS semicolon " ; " at
the end of the line.

Use Semicolon

//instead of
alert( 'I am not using semicolon' )
//please use
alert( 'I am using semicolon' );

Use === Instead of ==


JavaScript utilizes two different kinds of equality operators: === | !== and == | != It is considered best practice to
always use the former set when comparing.
"If two operands are of the same type and value, then === produces true and !== produces false." JavaScript: The Good Parts
However, when working with == and !=, you'll run into issues when working with different types. In these cases,
they'll try to coerce the values, unsuccessfully.
If you need numeric values to do Math operation then you can check if the value is a string '1234' or an integer 1234
in order to be able to do Math operation with numbers.

//behaviour example
var idNumber = '1352544'; //the value is a string not an integer
if( idNumber == 1352544 ){ // true in some browsers
//statements here
}
if( idNumber == '1352544' ){ // true in all browsers
//statements here
}
if( idNumber === '1352544' ){ //true in all browsers
//statements here
}
if( idNumber === 1352544 ){ //false in all browsers
//statements here
}

Emulating a private method with closure

Languages such as Java provide the ability to declare


methods private, meaning that they can only be called by

other methods in the same class.


JavaScript does not provide a native way of doing this, but it is possible to emulate private methods using closures.

Private methods aren't just useful for restricting access to


code: they also provide a powerful way of managing your
global namespace, keeping non-essential methods from
cluttering up the public interface to your code.
Here's how to define some public functions that can access private functions and variables, using closures which is
also known as the module pattern:

Private method with closure


var makeCounter = function() {
var privateCounter = 0;
function changeBy(val) {
privateCounter += val;
}
return {
increment: function() {
changeBy(1);
},
decrement: function() {
changeBy(-1);
},
value: function() {
return privateCounter;
}
}
};
var counter1 = makeCounter();
var counter2 = makeCounter();
alert(counter1.value()); /* Alerts
counter1.increment();
counter1.increment();
alert(counter1.value()); /* Alerts
counter1.decrement();
alert(counter1.value()); /* Alerts
alert(counter2.value()); /* Alerts

0 */

2 */
1 */
0 */

Object Constructor new Object()


HowTo detect old IE
JavaScript Commenting
JavaScript Style
Object Constructor new Object()
Omit the "Var" Keyword and Use Commas Instead

page_params Object
Understandability
Using class names for JS purposal
In order to make code reusable let's divide the objects in two modules (files): the object file with all the core
functionalities and the controller file with all the set up and events. Both should share the same filename but as for
the controller let's add the following suffix "_controller.js", meaining if we have a terminator.js file we should have a t
erminator_controller.js file.
As convention let's use the object name convention where the object name starts with capital letter.
In the above filename example for the terminator.js file it should contain the object with the core functionality for
instance:
Objects
var Terminator = function() {
"use strict";
var Self = this; // Self var instead of this in order to avoid confusion between
this according to object and this according to jquery or functionallity
/**
* Let's leave the object to know if the code is running in a legacy browser
*/
Self.objectVar_01 = " SOME VALUE IF NEEDED FOR THE OBJECT ";
/**
* Init method to set up more vars or initialite methods inside the object
*/
Self.init = function( options ){
Self.params = options; //Let's keep the Self.params var as default to access all
the params / options inside the object
!Self.objectVar_01 ? "THIS" : "THEN THAT" ; // In case we need to use our object
var
...AMAZING SET UP OR INIT METHODS HERE...
},
/**
* Method needed in the object
*/
Self.amazingMethod = function( location, newTag ){
...AMAZING CODE HERE...
};
}

Code for the terminator_controller.js should contain the whole set up for the object

Object_controller

var errorHandler = function( msg ){


console.log( "=======ERROR=======" );
console.log( msg );
console.log( "===================" );
};
try{
var blockRender = new Terminator();
blockRender.init({
'key' : value,
...AMAZING SET UP 'key' : value HERE...
});
}catch( e ){
errorHandler( e.message );
}

The idea about separating the object from the controller is to permit us the share the core functionalities even tho
there is a different set up, for instance, if there is a set up for pc ( elements and events ) and a different kind of set
up for mobile and tablets but all of them sharing the same core functionalities.In the above filename example for the
terminator_controller.js file it should contain the set up for the object.

Omit the "Var" Keyword and Use Commas Instead


HowTo detect old IE
JavaScript Commenting
JavaScript Style
Object Constructor new Object()
Omit the "Var" Keyword and Use Commas Instead
page_params Object
Understandability
Using class names for JS purposal

Omit the "Var" Keyword and Use Commas Instead


Long list of vars

//Instead of using var per each line


var someItem = 'some string';
var anotherItem = 'another string';
var oneMoreItem = 'one more string';
//use comma instead
var someItem = 'some string',
anotherItem = 'another string',
oneMoreItem = 'one more string';

...Should be rather self-explanatory. I doubt there's any real speed improvements here, but it cleans up your code a
bit.

page_params Object
HowTo detect old IE
JavaScript Commenting
JavaScript Style
Object Constructor new Object()
Omit the "Var" Keyword and Use Commas Instead
page_params Object
Understandability
Using class names for JS purposal
Coordinate with Back End the global values you need for the page, and make sure that all the data needed for the
page is inside that object. If you need more global or general data for the page then you can add the value to the
page_params object as depicted in the following image and code block.

page_params object set up

//Declare the var in the header


var page_params = {};
//Set up data in coordination with Back End
page_params = {
"video_id":"599361",
"video_hash":"8879764237c2b072d811e30e9aafd523",
"rating_up":669,
"rating_down":27,
"user_has_voted":false,
"segment":0,
"uploader_id":"0",
"download_cdn":"true",
"has_favorited":false,
"is_loggedin":false,
"has_voted":false,
"has_voted_direction":0,
"video_layout":"normal"
.....
};
//In case you need to add some global values to that object you can create your own
keys
page_params.jsUrl =
"http://front.tube8.gutierrez.trunk.nayul-tube8.na.manwin.local/mobile/js/";
page_params.video_urls = {};
page_params.video_urls.sd =
"http://cdn1.mobile.tube8.com/201101/23/599361/240P_358K_599361.mp4?sr=1200&int=6144
00b&nvb=20140916212825&nva=20140916232825&hash=0c6817364661629df00c0";
page_params.video_urls.hd =
"http://cdn1.mobile.tube8.com/201101/23/599361/240P_358K_599361.mp4?sr=1200&int=6144
00b&nvb=20140916212825&nva=20140916232825&hash=0c6817364661629df00c0";

Understandability
HowTo detect old IE
JavaScript Commenting
JavaScript Style
Object Constructor new Object()
Omit the "Var" Keyword and Use Commas Instead
page_params Object
Understandability
Using class names for JS purposal
Choose easy to understand and short names for variables and functions.

Bad variable names

var x1 = '',
fe2 = '',
xbqne = '',
incrementerForMainLoopWhichSpansFromTenToTwenty = '',
createNewMemberIfAgeOverTwentyOneAndMoonIsFull = '';

Avoid describing a value with your variable or function name.

//Might not make sense in some countries:


isOverEighteen();
//Works everywhere
isLegalAge();

Avoid using dash "-" as var name in javascript or class name in css, use camelcase and or underscore "_" to name
your vars and classes.
Var names

//Bad variable names


var my-div = document.getElementById( 'my-div' );
//Use camelcase and or underscore instead
var my_customDiv = document.getElementById( 'my_blockHtml' );

Your code is a story - make your storyline easy to follow!


Source: Javascript Best Practices

Using class names for JS purposal


HowTo detect old IE
JavaScript Commenting
JavaScript Style
Object Constructor new Object()
Omit the "Var" Keyword and Use Commas Instead
page_params Object
Understandability
Using class names for JS purposal

When a class is created in order to be used for javaScript purposes use "js_" as a prefix for this class name. It
doesn't matter if you are going to use that class name for CSS purposes.
HTML

<!--IN THE HTML-->


<div id="my_div" class="js_myClass">This div is used in JS and
CSS</div><!--/#my_div-->
<div id="my_SecondDiv" class="js_myClass">This div is used in JS and
CSS</div><!--/#my_SecondDiv-->
<div id="my_ThirdDiv" class="js_myClass">This div is used in JS and
CSS</div><!--/#my_ThirdDiv-->

CSS

/** IN CSS */
#my_div {
background-color: red;
}
#my_SecondDiv {
background-color: blue;
}
#my_ThirdDiv{
background-color: #000;
}
.js_myClass {
display: block;
width: 240px;
}

NOTE: avoid using "js_" prefixed classes or IDs for styling. It should be reserved just for JS.

JS

/** IN JAVASCRIPT */
var myDivs = document.getElementsByClassname( 'js_myClass' ),
i = 0,
j = myDivs.length;
for( ; i<j; i++ ){
//Do something with myDivs[i]
}

jQuery best practices


Selectors
Simplify your selectors

$( '#js-loadMore' ) // FASTER
$( '.greyButton' ) // SLOWER

When using class selectors, dont use the element type

var products = $( '.products' );// FASTER


var products = $( 'div.products' );// SLOWER

Avoid excessive specificity

$( '#more' )// FASTER


$( '#wrapper .underPlayer #more' )// SLOWER

Use find() for Id->Child nested selectors. The .find() approach is faster because the first selection is handled without
going through the Sizzle selector engine.

$( '#header' ).find( '.searchType' );// FASTER


$( '#header .searchType' )// SLOWER

Cache your selectors in variables

// Stores the live DOM element inside of a variable


var elem = $("#elem");
// Set's an element's title attribute using it's current text
elem.attr("title", elem.text());
// Set's an element's text color to red
elem.css("color", "red");
// Makes the element fade out
elem.fadeOut();

Use Chaining

// Stores the live DOM element inside of a variable


var elem = $("#elem");
// Chaining
elem.attr("title", elem.text()).css("color", "red").fadeOut();

Reduce DOM modifications


It's costly operation.

// Dynamically building an unordered list from an array


var localArr = ["Greg", "Peter", "Kyle", "Danny", "Mark"],
list = $("ul.people");
// DON'T do this
$.each(localArr, function(index, value) {
list.append("<li id=" + index + ">" + value + "</li>");
});
//Do this instead
var dynamicItems = "";
$.each(localArr, function(index, value) {
dynamicItems += "<li id=" + index + ">" + value + "</li>";
});
list.append(dynamicItems);

Event Handling

Delegate events, don't repeat yourself (DRY) and save


memory.
// Imagine a table of 1000 rows.
//This code attaches event handler to 1000 elements
$( "#dataTable tbody tr" ).on( "click", function() {
alert( $( this ).text() );
});
//This code attaches an event just to one element "tbody"
$( "#dataTable tbody" ).on( "click", "tr", function() {
alert( $( this ).text() );
});

Note: Avoid using too general parent selectors (like "document" or "body" or something 100500 steps away from the
target) to avoid long event "bubbling".

AJAX
Use promises, very flexible

// Regular code.
function getName(personid) {
var dynamicData = {};
dynamicData["id"] = personID;
$.ajax({
url: "getName.php",
type: "get",
data: dynamicData,
success: function(data) {
// Updates the UI based the ajax result
$(".person-name").text(data.name);
}
});
};
getName("2342342");

// More flexible code.


function getName(personid) {
var dynamicData = {};
dynamicData["id"] = personID;
return $.ajax({
url: "getName.php",
type: "get",
data: dynamicData
});
}
getName("2342342").done(function(data) {
// Updates the UI based the ajax result
$(".person-name").text(data.name);
});

// If we want to wait for two separate ajax requests done:


var person1 = getName("2342342"),
person2 = getName("3712968"),
people = [person1, person2];
$.when.apply(this, people).then(function() {
// Both the ajax requests have completed
});

Load Files via OCS


Description
OCS is a javaScript code practice, the idea is to create an Object file, a Controller file, and a Set Up file.

The Controller should get the Settings values via page_params object defined in the template.
In order to load the files Head.js plug in should be used creating the javascript files url array via Load_scripts Object
In the image below you can see the OCS file combo where the file on top is the Object, the file in the middle is the
Controller and the bottom file is the load files Set Up.

The file structure


Make sure the create a main set Up File, the goal of this file is to load the object files when needed, either on page
load or on any specific event. The file load would be executed via Load_scripts Object. It would be nice to have a
folder per object and inside this folder make sure the place the object file and the controller file as depicted in the
graphic below.

The Object file


Ideally the object file name should coincide with the object name. This file contains ONLY the object.

Object file example

//OBJECT TEMPLATE
var Top_ten_leaderboard = function(){
"use strict";
var Self = this;
Self.init = function( options ){
//AMAZING INIT FUNCTION HERE
},
/**
* AMAZING COMMENTS HERE
*/
Self.setUpTimeKeysJson = function(){
//AMAZING CODE HERE
},
/**
* AMAZING COMMENTS HERE
*/
Self.readCookie = function(){
//AMAZING CODE HERE
}
.....MORE AMAZING METHODS...
}

The Controller file


Ideally the controller file name should have the same Object file name follwed by "_controller.js" in order to be
consequent. Try to wrap the object init in try catch in order to avoid breaking the site in the case the object is not
loaded or has a problem by the time it was instanciated.
You can check the "errorHandler" function at the begining of this document.
Controller file code example

try{
var myLeaderBoard = new Top_ten_leaderboard();
myLeaderBoard.init({
'isLoggedin'
: page_params.isLoggedin,
'leaderBoardPlatform' : page_params.leaderBoardPlatform,
'intervalUpdate'
: page_params.intervalUpdate,
'ajaxUrl'
: page_params.leaderboardAjaxUrl,
'toplimit'
: page_params.toplimit,
});
} catch( e ){ errorHandler( 'myLeaderBoard set up: ' + e.message ); }

The Settings in the template


The Object settings are basically the set up. This settings should be sent to the Object via the Controller. Is very
important for this settings to use the "page_params" object in order to make familiar code for all the developers and
on top of that avoid global vars. You can check a quick explanation about page_params.
Object settings definition example

//VALUES ARE JUST AN EXAMPLE HOW TO USE page_params VAR ON PC VIEW


<script type="text/javascript">
page_params.isLoggedin = <?=( $userdata ? 1 : 0 )?>;
page_params.followAjaxUrl = "http://" + window.location.hostname +
"/ajax/userSubscriptions.php";
page_params.leaderboardAjaxUrl = 'http://' + window.location.hostname +
'/ajax/getLeaderBoardTop.php';
page_params.toplimit = 10;
page_params.leaderBoardPlatform = "pc";//GOOD EXAMPLE OF SETTING UP A VALUE ON PC
page_params.intervalUpdate = true;
page_params.animate = true;
//LISTING SET UP FILE
customJs.push(jsUrl + "leaderBoard_setUp" + urlSuffix);
</script>
//VALUES ARE JUST AN EXAMPLE HOW TO USE page_params VAR ON TABLET VIEW
<script type="text/javascript">
page_params.isLoggedin = <?=( $userdata ? 1 : 0 )?>;
page_params.followAjaxUrl = "http://" + window.location.hostname +
"/ajax/userSubscriptions.php";
page_params.leaderboardAjaxUrl = 'http://' + window.location.hostname +
'/ajax/getLeaderBoardTop.php';
page_params.toplimit = 10;
page_params.leaderBoardPlatform = "tablet";//GOOD EXAMPLE OF SETTING UP A VALUE ON
TABLET
page_params.intervalUpdate = false;
page_params.animate = false;
//LISTING SET UP FILE
customJs.push(jsUrl + "leaderBoard_setUp" + urlSuffix);
</script>

The File load Set up


This set up function is the way to build js file array list to be loaded via Load Scripts Object.
In order to be consistent the jsFileList should all the time contain two arrays "core" and "controller", where in the core
array object files and main functionality should be listed whereas in "controller" controller files should be listed.

The Set Up function

try{
/**
* THE GOAL IS TO MIGRATE THE FILE PUSH
* TO generalFileList FUNCTION
*/
var generalFileList = function(){
var jsPage = new Load_scripts(),
jsFileList = {};
jsFileList.core = []; //PUSH HERE WHAT IS CONSIDER CORE FILES
jsFileList.controller = []; //PUSH HERE WHAT IS CONSIDER CONTROLLER FILES
/**
* PUSH FILE LIST HERE
* in the jsFileList object there is two arrays
* push in these arrays the filenames needed
*/
jsFileList.core.push( "JAVASCRIPT CORE FILE URL HERE" );
jsFileList.controller.push( "JAVASCRIPT CONTROLLER FILE URL HERE" );
jsPage.init({
'jsFileList' : jsFileList, //json object with file list
'head'
: head //head.js plugin object
});
};
generalFileList();
}catch( e ){ errorHandler( 'Load files desktop general set up: ' + e.message ) }

The code below is an example of the set up explaned above


Set up code example

try{
/**
* NETWORK BAR set up
*/
var ph_bar = new PornhubNetworkBar(
'PornhubNetworkBar',
'tube8',
page_params.segment,
false,
'body { background-position: 0 24px;} ' +
'div.bar_body div.bar_items { width:992px;} ',
true //checking if tablet or not
),
generalLoadFiles = function(){
var tabletLoadFiles = new Load_scripts(),
jsFileList = {};

jsFileList.core = [];
jsFileList.controller = [];
/**
* TE-5396
* German disclaimer
*/
if( page_params.showDisclaimer ){
jsFileList.core.push( urlPrefix + 'german_disclaimer/german_disclaimer' +
urlSuffix );
jsFileList.controller.push( urlPrefix +
'german_disclaimer/german_disclaimer_controller' + urlSuffix );
}
/**
* TE-5373 Set up
* MG autocomplete set up
*/
jsFileList.core.push( urlPrefix + 'autocomplete/autocomplete' + urlSuffix );
jsFileList.controller.push( urlPrefix + 'autocomplete/autocomplete_controller' +
urlSuffix );
/**
* Segment changer (tablet only)
*/
jsFileList.core.push( urlPrefix + 'segment_changer/segment_changer' +

urlSuffix

);
jsFileList.controller.push( urlPrefix +
'segment_changer/segment_changer_controller' +

urlSuffix );

/**
* TE-5383
* Search bar show (tablet only) (tablet only)
*/
jsFileList.core.push( urlPrefix + 'searchbar_show/searchbar_show' + urlSuffix );
jsFileList.controller.push( urlPrefix + 'searchbar_show/searchbar_show_controller'
+ urlSuffix );
tabletLoadFiles.init({
'jsFileList' : jsFileList,
'head'
: head
});
};

generalLoadFiles();
}catch( e ){ errorHandler( 'Tablet general file load: ' + e.message ) }

SVN Guidelines
Commenting
When comitting make sure you use the same comment in both SVN and JIRA ticket:

TASK-NUMBER
TASK TITLE HERE
[+] What you added or modified ( function, file or piece of code )
[-] What you remove ( file, function or piece of code )
Note:
If you have something extra to say

Committed in:
http://URL_HERE
At revision: REVISION NUMBER HERE

Follow the example below

TE-5167
Mobile Touch: Build ads using Javascript
[+] changing quotation marks
[-] Removing code no longer needed
committed in:
http://svn.tubes.na.manwin.local/tube8.com/main/trunk
At revision: 10333

You might also like