On Github khan4019 / HighPerformanceJSandCSS
1. <html> 2. <body> 3. <p> 4. Hello World 5. </p> 6. <div> 7. <img src="example.png"/> 8. </div> 9. </body> 10. </html>How Browser Works
Don’t Just Wrap a DIV Around It
p,div{ margin-top:3px; } .error { color:red; }
Use DOM DocumentFragment
1. <style> 2. #myFirstTODO 3. { 4. color:red; 5. } 6. </style> 7. 8. <div> 9. <p id="myFirstTODO"> have to shower </p> 10. <p> have to shave</p> 11. <p> have to cut hair</p> 12. <p> buy perfume</p> 13. <p> at least buy t shirt</p> 14.
1. <style> 2. .greenBold 3. { 4. color: green; 5. font-weight:bold; 6. } 7. </style> 8. 9. <div> 10. <p> have to shower</p> 11. <p class="greenBold"> have to shave</p> 12. <p class="greenBold"> have to cut hair</p> 13. <p> buy perfume</p> 14. <p> at least buy t shirt</p> 15.
1. <style> 2. li > ul 3. { 4. color: green; 5. font-weight: bold; 6. } 7. </style> 8. 9. <div> 10. <ul> 11. <li> List Item 12. <ul> 13. <li> Child </li> 14. </ul> 15. </li> 16. <li> List Item </li> 17. <li> List Item </li> 18. <li> List Item </li> 19. </ul> 20.
#myTODO p { color: green; font-weight: bold; }
body * { color:#365277; } .hide-scrollbars * { font-size: 16px; }
#myDiv ul li button { width:200px; } #myDiv ul li:nth-child(2) li:nth-child(7) > a { color:red; }
.btnMedium { width:200px; } .myClass { color:red; }
.upTrend { background-image:url('upGreen.jpg'); background-repeat:no-repeat; background-position: center center; padding-left:20px; } .downTrend { background-image:url('downRed.jpg'); background-repeat:no-repeat; background-position: center center; padding-left:20px; }
.upTrend { background-image:url('upGreen.jpg') center center no-repeat; padding-left:20px; } .downTrend { background-image:url('downRed.jpg') center center no-repeat; padding-left:20px; }
.upTrend { background-image:url('upGreen.jpg'); } .downTrend { background-image:url('downRed.jpg'); } .upTrend, .downTrend { background-repeat:no-repeat; background-position: center center; padding-left:20px; }DRYer CSS
ul li a { /* My awesome anchor */ } * html #atticPromo ul li a { /* My awesome rules */ }
ul #top_blue_nav { ... } form #UserLogin { ... }
//don't treeitem[IsImapServer="true"] > treerow > .tree-folderpane-icon { ... } //do .tree-folderpane-icon[IsImapServer="true"] { ... }Mozilla Rendering Guides
1. <html> 2. <head> 3. //head omitted due to lack of brain 4. </head> 5. <body> 6. <header> 7. <h1>My Awesome title</h1> 8. </header> 9. <nav> 10. <ol> 11. <li><a href="#">StackOverflow</a></li> 12. <li><a href="#">StackOverflow</a></li> 13. </ol> 14. </nav> 15. <section> 16. <div> 17. <ul> 18. <li><a href="#">StackOverflow</a></li> 19. <li><a href="#">StackOverflow</a></li> 20. </ul> 21. </div> 22. </section> 23. </body> 24.</html>
/* Take Advantage of CSS specificity */ /* class, id, inline, !important */Estelle Weyl: CSS SpeciFISHity CSS-Tricks: CSS Specificity Understanding CSS MDN: Specificity Specificity calculator Power of Specificity CSS Specificity: Things you should know
var blah = document.getElementById('myID'); var blah2 = document.getElementById('myID2'); var blah3 = document.getElementById('myID3'); var blah = document.getElementById('myID'), blah2 = document.getElementById('myID2'), blah3 = document.getElementById('myID3');
var doc = document, blah = doc.getElementById('myID'), blah2 = doc.getElementById('myID2'), blah3 = doc.getElementById('myID3');
for(var i = 0; i < someArray.length; i++) { var container = document.getElementById('container'); container.innerHtml += 'my number: ' + i; console.log(i); }
var container = document.getElementById('container'); for(var i = 0; i < someArray.length; i++) { container.innerHtml += 'my number: ' + i; console.log(i); }
var container = document.getElementById('container'); for(var i = 0, len = someArray.length; i < len; i++) { container.innerHtml += 'my number: ' + i; console.log(i); }
var i, length = 100; for ( i = 0; i < length; i++ ) { // statements } // Or... var i = 0, length = 100; for ( ; i < length; i++ ) { // statements }Idiomatic JS
0 == ''; // true 0 === false; //false
if (( x === null) || (x === undefined)){ ... } if(x == null) { ... }
When you don't actually know whether they are same type
typeof thing == 'function'; //always be string myArray.length == 0; //will always be number mySting.indexOf('x') == 0;bReaK aLL thE RuleZ
if ( !MyNamespace ) { var MyNamespace = { }; } //or var myNamespace = myNamespace || {}; //or http://jsperf.com/conditional-assignment // myNamespace || ( myNamespace = {} ); //or if ( typeof MyNamespace == ’undefined’ ) { var MyNamespace = { }; }Nokia: JS Best Practice
var tinyMessage = 'Trust me, i started one line' + 'Designer told me he wants little more' + 'I added little more' + 'Manager said, this is not enough' + "He didn't said what to add" + 'Just said add' + "I didn't know what to add" + 'So i added a slice of pizza' + 'Client said this is stupid' + 'Manager said, client is right';Optimize JavaScript
var tinyMessage = ['Trust me, i started one line', 'Designer told me he wants little more', 'I added little more', 'Manager said, this is not enough', "He didn't said what to add", 'Just said add', "I didn't know what to add", 'So i added a slice of pizza', 'Client said this is stupid', 'Manager said, client is right'].join(' ');array-join-vs-string-connect Why is string concatenation faster than array join fastest-way-to-build-this-string
var strBuilder = ['First 20 fibonacci numbers:']; for (var i = 0; i < 20; i++) { strBuilder.push( i, '=', fibonacci(i)); } var fibonacciStr = strBuilder.join(' ');
// Don't do this: a = []; // executor knows nothing for(var i = 1; i <= 4; i++) { a.push(i); } // just do it: var a = [1, 2, 3, 4];
var myArray = [1, 2, 3, 4, 5, 6]; //myArray.length = 6 delete myArray[2]; myArray; //[1, 2, undefined × 1, 4, 5,6] console.log(myArray.length); // 6 console.log(myArray[2]); // undefined
myArray.splice(2,1);
var o = { x: 1 }; delete o.x; // true o.x; // undefined
function getLargeThing (x) { var a = function () { var largeStr = new Array(1000000).join('x'); return function () { return largeStr; }; }();Fast Memory Efficient JavaScript JSPerf: Closure vs Shared method
if (callback && typeof callback === "function"){ /* rest of your logic */ }else{ /* not a valid function */ }JavaScript Code Review
var fibonacci = function (n) { return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2); }; for (var i = 0; i <= 10; i += 1) { console.log( i + ': ' + fibonacci(i)); } // 0: 0 // 1: 1 // 2: 1 // 3: 2 // 4: 3 // 5: 5 // 6: 8 // 7: 13 // 8: 21 // 9: 34 // 10: 55
var fibonacci = (function () { var memo = [0, 1]; var fib = function (n) { var result = memo[n]; if (typeof result !== 'number') { result = fib(n - 1) + fib(n - 2); memo[n] = result; } return result; }; return fib; })();
Function.prototype.memoize = function(){ var self = this, cache = {}; return function( arg ){ if(arg in cache) { console.log('Cache hit for '+arg); return cache[arg]; } else { console.log('Cache miss for '+arg); return cache[arg] = self( arg ); } } }Addy Osmani: Faster JS Memoization
function fooBar(a){ ... } // once a memoizer is available, usage is as simple as var memoFooBar = fooBar.memoize(); memoFooBar(1); // are conducted. This result is then cached for next time. memoFooBar(1); // will now return the cached result memoFooBar(2); // whilst this will need to be calculatedAddy Osmani: Optimized Memoization Library
var current = null; function init(){...} function change(){...} function verify(){...}
var myNameSpace = { current:null, init:function(){...}, change:function(){...}, verify:function(){...} } myNameSpace.init();W3.org JS best practice Develop with Namespace JS 24 best practices
(function(){ var current = null; function init(){...} function change(){...} function verify(){...} })();
(function( skillet, $, undefined ) { //Private Property var amountOfGrease = "1 Cup"; //Public Method skillet.toString = function() { console.log( skillet.quantity + " " + skillet.ingredient + " & " + amountOfGrease + " of Grease" ); console.log( isHot ? "Hot" : "Cold" ); }; }( window.skillet = window.skillet || {}, jQuery ));
// Non-strict code... (function(){ "use strict"; // Define your library strictly... })(); // Non-strict code...John Resig: Strict Mode
$(document).ready(function () { alert('document is ready. I can sleep now'); });
document.onreadystatechange = function () { //docuemnt ready. dont work for older browser or IE if (document.readyState == "complete") { alert('document is ready. I can sleep now'); } }
$('#myText').css("color", "blue"); $('#myText').css("font-size", "1.2em"); $('#myText').text("Text changed!");
//chain it or cache it $('#myText').css({ "color": "blue", "font-size": "1.2em"}).text("Text changed!");
//better .myClass{ color:blue; font-size:1.2em; } //apply class not style $('#myText').addClass('myClass').text("Text changed!");Efficient JQuery Selector
<ul class="nav"> <li>List 1, item 1</li> <li>List 1, item 2</li> <li>List 1, item 3</li> </ul> <ul class="nav"> <li>List 2, item 1</li> <li>List 2, item 2</li> <li>List 2, item 3</li> </ul>
$( "ul.nav li:eq(1)" ).css( "backgroundColor", "#ff0" ); //better $( "ul.nav" ).each(function( index ) { $( this ).find( "li:eq(1)" ).css( "backgroundColor", "#ff0" ); });
Remember :=> JQuery is not Database
jquery-performance-rules 15-powerful-jquery-tips-and-tricksEvery byte counts
<script src="file-a.js"></script> <script src="file-b.js" defer></script> <script src="file-c.js" async></script>Async Vs Defer
Browser dynamically adjust to keep frame rate normal.
Decouple events from animation
Avoid animation that causes reflow-repaint loops
HTML5: faster rFA rFA API: sub milisecond precision can i use: rFAwindow.onscroll = function(e) { var parallax = document.getElementById('parallax-background'); parallax.style.marginTop = (window.scrollY/2) + 'px'; }
window.onscroll = function(e) { // could use prefixes: webkitTransform, mozTransform etc. var parallax = document.getElementById('parallax-background'); parallax.style.transform = 'translate3d(0px,' + (window.scrollY/2) + 'px, 0px)'; }Flickr: Parallax
//test console.assert(myArray.length >5, "More than 5 elements"); //hit count console.count("Number of times entered"); //JS represents of Obj console.dir(document.body); //trace console.trace();Using the console Console API
console.time("Array initialize"); var array= new Array(1000000); for (var i = array.length - 1; i >= 0; i--) { array[i] = new Object(); }; console.timeEnd("Array initialize");
var start = performance.now(); //execute your function foobar(); var end = performance.now(); console.log(start - end +'ms');Axel Rauschmayer: JS Console API CodeSchool: Discover Dev Tools
\
/
As Long As YOU know what YOU ARE doing
Break All the Rules