Front End Best Practices

40
1. Guidelines and Best Practices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 1.1 CSS Guidelines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 1.2 Good Reads and Links . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 1.3 High Performance JS tips . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 1.4 HTML Guidelines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 1.5 Javascript Guidelines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 1.5.1 HowTo detect old IE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 1.5.2 JavaScript Commenting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 1.5.3 JavaScript Style . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 1.5.4 Object Constructor new Object() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 1.5.5 Omit the "Var" Keyword and Use Commas Instead . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26 1.5.6 page_params Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27 1.5.7 Understandability . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28 1.5.8 Using class names for JS purposal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29 1.6 jQuery best practices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31 1.7 Load Files via OCS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34 1.8 SVN Guidelines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40

description

Front End Best Practices

Transcript of Front End Best Practices

  • 1. Guidelines and Best Practices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21.1 CSS Guidelines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31.2 Good Reads and Links . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91.3 High Performance JS tips . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101.4 HTML Guidelines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101.5 Javascript Guidelines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

    1.5.1 HowTo detect old IE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121.5.2 JavaScript Commenting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131.5.3 JavaScript Style . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141.5.4 Object Constructor new Object() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241.5.5 Omit the "Var" Keyword and Use Commas Instead . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261.5.6 page_params Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271.5.7 Understandability . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281.5.8 Using class names for JS purposal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29

    1.6 jQuery best practices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311.7 Load Files via OCS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341.8 SVN Guidelines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40

  • Guidelines and Best Practices

    General

    Coding standards specify a common format for the source code and comments. This allows developers to easilyshare code and , and the ideas expressed within the code and comments, between each other. Having a standardcreates 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 thepast, but it's important to know that this is now being superseded by a leaner and meaner snippet.

    Ideally, the HTML5 DOCTYPE should be used. It's supported in all modern browsers, and throws IE6 and IE7 intostandards mode. .Source

    Use Tables for Tabular Data Only

    Tables should only ever be used for the presentation of tabular data. The only exception is when composing HTMLemail, in which a table is almost the only thing supported by soul crushing email clients.

    For accessibility, table headers should always be presented using elements. Remember to also set cellpad, and values to as these are more consistently controlled by CSS.ding cellspacing border 0

    Error Handler function

    Error Handler Function

    var errorHandler = function( msg ){ try{ console.error( "=======ERROR=======" ); console.error( msg ); console.error( "===================" ); }catch( e ){};};

    Indentation

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

    http://ejohn.org/blog/html5-doctype/
  • 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 developersto tag parts of a stylesheet with important meta information. Eventually it may be used to provide an enhancedinterface in your favorite IDE. Although it is still in the draft phase, CSSDOC is a great way to clean up yourstylesheets.

    Syntax

    This is the basic block in which all comments will be placed. It has a very specific markup. The opening line has oneforward slash followed by two asterisks. Each comment line thereafter should start with a single space an asteriskand 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 andsome 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 aboutthe 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 typicallyfind 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 agreat 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 worksaround 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 usethis tag.

    NAMING

    ID and Class Naming

    Use meaningful or generic ID and class names. Instead of presentational or cryptic names, always use IDand class names that reflect the purpose of the element inquestion, or that are otherwise generic. Names that are specific and reflect the purpose of theelement should be preferred as these are mostunderstandable and the least likely to change. Generic names are simply a fallback for elements that haveno 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 aslong 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 caseswhere only one value is explicitly set.

    Using shorthand properties is useful for code efficiency and understandability.

    http://www.w3.org/TR/CSS21/about.html#shorthand
  • /* 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 that does the sorting for youCSScomb

  • #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 andre-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 avery 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 theObject and Function objects.

    Partial Application in JavaScript, by Ben Alman

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

    https://github.com/stevekwan/best-practices/blob/master/javascript/best-practices.md#javascript-the-good-parts-by-douglas-crockfordhttp://shop.oreilly.com/product/9780596517748.dohttps://github.com/stevekwan/best-practices/blob/master/javascript/best-practices.md#best-practices-for-speeding-up-your-site-by-the-yahoo-developer-networkhttp://developer.yahoo.com/performance/rules.htmlhttps://github.com/stevekwan/best-practices/blob/master/javascript/best-practices.md#constructors-considered-mildly-confusing-by-joost-diepenmaathttp://joost.zeekat.nl/constructors-considered-mildly-confusing.htmlhttps://github.com/stevekwan/best-practices/blob/master/javascript/best-practices.md#jquery-apihttp://api.jquery.com/https://github.com/stevekwan/best-practices/blob/master/javascript/best-practices.md#if-youre-a-javascript-ninja-read-thesehttps://github.com/stevekwan/best-practices/blob/master/javascript/best-practices.md#the-surprisingly-elegant-javascript-type-model-by-kannan-vijayanhttp://vijayan.ca/blog/2012/02/21/javascript-type-model/https://github.com/stevekwan/best-practices/blob/master/javascript/best-practices.md#javascript-object-vs-function-experiment-by-steve-kwanhttps://github.com/stevekwan/experiments/blob/master/javascript/object-vs-function.htmlhttps://github.com/stevekwan/best-practices/blob/master/javascript/best-practices.md#partial-application-in-javascript-by-ben-almanhttp://benalman.com/news/2012/09/partial-application-in-javascript/
  • JavaScript constructor vs prototype experiment, by Steve Kwan

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

    High Performance JS tips

    Put all 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 GuidelinesNaming Classes and Id's

    Avoid using dash "-" in classes or HTML id's use camelCase or underscore "_" instead.

    Clickme Clickme

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

    https://github.com/stevekwan/best-practices/blob/master/javascript/best-practices.md#javascript-constructor-vs-prototype-experiment-by-steve-kwanhttps://github.com/stevekwan/experiments/blob/master/javascript/constructor-vs-prototype.html
  • Clickme

    Clickme

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

    Clickme

    Quotation mark

    Use double quotes all the time for HTML attribute values.

    HTML Quotation Mark

    Clickme

    COMMENTING CLOSING DIVS

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

  • HTML

    Amazing HTML code here Amazing HTML code here Amazing HTML code here

    Multiline properties

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

    Multiline HTML properties

    Javascript Guidelines

    Use semicolon after "use strict"Put semicolon on the last method inside the objects.HowTo detect old IE

    HowTo detect old IEJavaScript CommentingJavaScript StyleObject Constructor new Object()

  • Omit the "Var" Keyword and Use Commas Insteadpage_params ObjectUnderstandabilityUsing class names for JS purposal

    HowTo detect old IE without checking User Agent string

    Checking old IE without User Agent String

    var page_params = { isOldIE : false};

    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 IEJavaScript CommentingJavaScript StyleObject Constructor new Object()Omit the "Var" Keyword and Use Commas Insteadpage_params ObjectUnderstandabilityUsing 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 IEJavaScript CommentingJavaScript Style

    http://usejsdoc.org/about-getting-started.html
  • Object Constructor new Object()Omit the "Var" Keyword and Use Commas Insteadpage_params ObjectUnderstandabilityUsing 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 OFvar myArray = [ "cabeza", "tronco", "extremidades".... ]; for( var i=0; i

  • 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

  • Multiline statements

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

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

    Beautiful Syntax

    always have spaces, braces and span multiple linesif / else / for / while / try this encourages readability.

  • Parens, Braces, Linebreaks

    var i = 0, length = 100;

    for( ; i

  • Script Tag

    // code here

    or// code here DO NOT use (some IDEs still generate it):

    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:

    //Goodvar o = new Object();o.name = 'Carlitos';o.lastName = 'Way';o.someFunction = function() { console.log( this.name );} //Bettervar 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

    //goodvar a = new Array();a[0] = 'Carlitos';a[1] = 'Way'; //bettervar a = [ 'Carlitos', 'Way' ];

    Use JSON

    When storing data structures as plain text or sending/retrieving data structures via Ajax, use JSON instead of XMLwhen possible. JSON (JavaScript Object Notation) is a more compact and efficient data format, and islanguage-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 beused. If it exists in your page, there is almost always a more correct way to accomplish what you are doing. Forexample, 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 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 beforenoticing any progress.

    If you have JS files whose only purpose is to add functionality -- for example, after a button is clicked -- go aheadand place those files at the bottom, just before the closing body tag. This is absolutely a best practice.

    http://www.javascripttoolbox.com/bestpractices/#squarebracket
  • And now you know my favorite kinds of corn.

    var amazingVar = "amazing string"; ... AMAZING CODE NEEDED HERE ( IF NOT POSSIBLE TO PUT IN AN EXTERNAL FILE ) ...

    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 getvalues from back end in the page please place the script at the end of the template.

  • Avoiding inline javaScript

    Copyright 2007-2014 Tube8.com, All Rights Reserved: /*** 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} Copyright 2007-2014 Tube8.com, All Rights Reserved:

    Always, Always Use Semicolons

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

  • Use Semicolon

    //instead ofalert( 'I am not using semicolon' ) //please usealert( '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 1234in order to be able to do Math operation with numbers.

    //behaviour examplevar 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 declaremethods 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 tocode: they also provide a powerful way of managing yourglobal namespace, keeping non-essential methods fromcluttering 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 isalso 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 0 */counter1.increment();counter1.increment();alert(counter1.value()); /* Alerts 2 */counter1.decrement();alert(counter1.value()); /* Alerts 1 */alert(counter2.value()); /* Alerts 0 */

    Object Constructor new Object()

    HowTo detect old IEJavaScript CommentingJavaScript StyleObject Constructor new Object()Omit the "Var" Keyword and Use Commas Instead

  • page_params ObjectUnderstandabilityUsing 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 corefunctionalities and the controller file with all the set up and events. Both should share the same filename but as forthe controller let's add the following suffix "_controller.js", meaining if we have a file we should have a terminator.js t

    file.erminator_controller.js

    As convention let's use the object name convention where the object name starts with capital letter.

    In the above filename example for the file it should contain the object with the core functionality for terminator.jsinstance:

    Objects

    var Terminator = function() { "use strict"; var Self = this; // Self var instead of this in order to avoid confusion betweenthis 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 allthe params / options inside the object !Self.objectVar_01 ? "THIS" : "THEN THAT" ; // In case we need to use our objectvar ...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 thothere is a different set up, for instance, if there is a set up for pc ( elements and events ) and a different kind of setup for mobile and tablets but all of them sharing the same core functionalities.In the above filename example for the

    file it should contain the set up for the object. terminator_controller.js

    Omit the "Var" Keyword and Use Commas Instead

    HowTo detect old IEJavaScript CommentingJavaScript StyleObject Constructor new Object()Omit the "Var" Keyword and Use Commas Insteadpage_params ObjectUnderstandabilityUsing 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 insteadvar 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 abit.

    page_params Object

    HowTo detect old IEJavaScript CommentingJavaScript StyleObject Constructor new Object()Omit the "Var" Keyword and Use Commas Insteadpage_params ObjectUnderstandabilityUsing 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 thepage is inside that object. If you need more global or general data for the page then you can add the value to thepage_params object as depicted in the following image and code block.

  • page_params object set up

    //Declare the var in the headervar page_params = {}; //Set up data in coordination with Back Endpage_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 ownkeyspage_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=614400b&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=614400b&nvb=20140916212825&nva=20140916232825&hash=0c6817364661629df00c0";

    Understandability

    HowTo detect old IEJavaScript CommentingJavaScript StyleObject Constructor new Object()Omit the "Var" Keyword and Use Commas Insteadpage_params ObjectUnderstandabilityUsing 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 everywhereisLegalAge();

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

    Var names

    //Bad variable namesvar my-div = document.getElementById( 'my-div' ); //Use camelcase and or underscore insteadvar 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 IEJavaScript CommentingJavaScript StyleObject Constructor new Object()Omit the "Var" Keyword and Use Commas Insteadpage_params ObjectUnderstandabilityUsing class names for JS purposal

    http://www.thinkful.com/learn/javascript-best-practices-1/Make-it-Understandable
  • When a class is created in order to be used for javaScript purposes use "js_" as a prefix for this class name. Itdoesn't matter if you are going to use that class name for CSS purposes.

    HTML

    This div is used in JS andCSSThis div is used in JS andCSSThis div is used in JS andCSS

    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( ; iChild nested selectors. The .find() approach is faster because the first selection is handled withoutgoing 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 textelem.attr("title", elem.text());

    // Set's an element's text color to redelem.css("color", "red");

    // Makes the element fade outelem.fadeOut();

    Use Chaining

    // Stores the live DOM element inside of a variable var elem = $("#elem");

    // Chainingelem.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("" + value + ""); }); //Do this insteadvar dynamicItems = "";

    $.each(localArr, function(index, value) { dynamicItems += "" + value + "";});list.append(dynamicItems);

    Event Handling

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

    // 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() );});

    : Avoid using too general parent selectors (like "document" or "body" or something 100500 steps away from theNotetarget) 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 theController 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 pageload or on any specific event. The file load would be executed via . It would be nice to have aLoad_scripts Objectfolder per object and inside this folder make sure the place the object file and the controller file as depicted in thegraphic below.

    The fileObject

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

    http://wiki.na.manwin.local/display/ph/Load_scripts+objecthttp://wiki.na.manwin.local/display/ph/Load_scripts+object
  • Object file example

    //OBJECT TEMPLATEvar 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 fileController

    Ideally the controller file name should have the same Object file name follwed by "_controller.js" in order to beconsequent. Try to wrap the object init in try catch in order to avoid breaking the site in the case the object is notloaded 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 in the templateSettings

    The Object settings are basically the set up. This settings should be sent to the Object via the Controller. Is veryimportant for this settings to use the "page_params" object in order to make familiar code for all the developers andon 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 page_params.isLoggedin = ; 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); //VALUES ARE JUST AN EXAMPLE HOW TO USE page_params VAR ON TABLET VIEW page_params.isLoggedin = ; 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 ONTABLET page_params.intervalUpdate = false; page_params.animate = false;

    //LISTING SET UP FILE customJs.push(jsUrl + "leaderBoard_setUp" + urlSuffix);

    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 corearray object files and main functionality should be listed whereas in "controller" controller files should be listed.

    http://wiki.na.manwin.local/display/ph/Javascript+Guidelineshttp://wiki.na.manwin.local/display/ph/Load_scripts+object
  • 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_HEREAt revision: REVISION NUMBER HERE

    Follow the example below

    TE-5167Mobile 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

    Guidelines and Best PracticesCSS GuidelinesGood Reads and LinksHigh Performance JS tipsHTML GuidelinesJavascript GuidelinesHowTo detect old IEJavaScript CommentingJavaScript StyleObjectConstructor new Object()Omit the "Var" Keyword and Use Commas Insteadpage_params ObjectUnderstandabilityUsing class names for JS purposaljQuery best practicesLoad Files via OCSSVN Guidelines