Professional Documents
Culture Documents
2
3
9
10
10
12
12
13
14
24
26
27
28
29
31
34
40
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>
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.
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
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
/**
* 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 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.
NAMING
ID and Class Naming
/* Recommended: specific */
#gallery {}
#login {}
.video {}
/* Recommended: generic */
.aux {}
.alt {}
/* 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;
.myClass {
bottom: 0;
font-size: 12px;
margin: 0;
padding: 3px 0;
}
#header {
display: block;
}
.logo {
display: block;
}
Put a space before the { in rules declaration & a space after : in property
#header {
display: block;
}
/**
* 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;
}
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.
jQuery API
jQuery is essential for the modern JavaScript developer. Consult their API docs to learn all the library has to offer.
/* 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-->
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.
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-->
HTML
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;site_id=13&amp;c
ache=1410991481&amp;c=HomePage&amp;channel[Searched_Terms]=HomePage"
data-adzone="12345"></iframe>
Javascript Guidelines
<script>
var page_params = {
isOldIE : false
};
</script>
<!--[if lte IE 8 ]>
<script> page_params.isOldIE = true; </script>
<![endif]-->
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
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
}
/**
* 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
}
JavaScript Style
HowTo detect old IE
JavaScript Commenting
JavaScript Style
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);
}
if( foo ){
alert( 'Hello world!' );
}
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.
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">
//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.
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."
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.
<div id="footer-copyright">
<span id="copyright">Copyright © 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 © 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-->
Use Semicolon
//instead of
alert( 'I am not using semicolon' )
//please use
alert( 'I am using semicolon' );
//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
}
0 */
2 */
1 */
0 */
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
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.
...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.
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.
var x1 = '',
fe2 = '',
xbqne = '',
incrementerForMainLoopWhichSpansFromTenToTwenty = '',
createNewMemberIfAgeOverTwentyOneAndMoonIsFull = '';
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
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
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]
}
$( '#js-loadMore' ) // FASTER
$( '.greyButton' ) // 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.
Use Chaining
Event Handling
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");
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.
//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...
}
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 ); }
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 ) }
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
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