How it works?
HTML + JS + CSS
+
Magic
of Browser
=
Web App
Why Should I Know How Browser Works?
To feel that you are in control,
To justify why you did it "that" way,
To sound cool in tech conversations...
What is a Browser?
"Present Content from location in URI"
- HTML
- PDF
- Text
- Image
...
"as per specification provided by W3C"
well... almost
Components
-
User Interface - address Bar, Back, Forward, Bookmark, etc
-
Browser Engine - Intermediary between UI & Rendering Engine
-
Rendering Engine - Parse & Display Content
-
Networking - abstract interface for network requests (like HTTP)
-
UI Backend - Generic interface for basic widgets
-
Javascript Interpreter - Parse & Execute Javascript code
-
Data Storgage - Cookies/LocalStorage/IndexedDB/WebSQL/FileSystems
Rendering Engines
- Internet Explorer => Trident
- Firefox => Gecko
- Safari => WebKit
- Chrome => Blink (WebKit)
- Opera => Blink (WebKit)
We will discuss about WebKit henceforth...
Why?
QUIZ Time
HTML === XML?
What is the difference?
"HTML is forgiving"
Hence, the parsing complexity...
DOM Tree
<html><body>
<p>Hello World</p>
<div><img src="example.png"/></div>
</body></html>

Ok, I understand DOM, but what is BOM?
WebKit CSS Parsing
Context Free Grammar --> Easy to Parse
Execution Order
Scripts - Inherent model is synchronous
Sequential -> Fetch + Parse + Execute
Solution: Defer/Async/Speculative
CSS - Order does not matter as CSS does not modify DOM
But, what if scripts want to query CSS?
WebKit - blocks script only if CSS is referred
Stylesheets @ HEAD
Javascripts @ EOB
... unless your JS would modify the layout :-/
Render Tree
Ordered Tree of Visual Elements
RenderObject represent a rectangular area
& knows how to paint itself & its children.
RenderObject <-/-> DOM Element
example - Head, Complex DOM Elements & elements with "Display:None"
Render Tree Example
Attachments...
Style Hierarchy
Cascade Order
- Browser Declaration
- User Normal Declaration
- Author Normal Declaration
- Author Important Declaration
- User Important Declaration
What if the declarations are of same type?
Solution: Specificity
Specificity
!important automatically wins!
Specificity Score Examples

Specificity Hands-on Example
Layout
Flow
Left to Right
Top to Bottom
Recursive
Relative to Root (0,0)
Re-Layout
Global (Synch)
(example - Font Change)
or
Incremental (async) - Dirty Bit
Dirty Bit is set if added/modified
2 Dirty Flags - Self/Children
(example - text inserted in text fields)
CSS Box Model
Each node generates 0..n boxes
CSS Box Model
Box Type depends on Display Property
Positioning Scheme
[Position Property + Float Attribute]
-
Normal [Static & Relative]
Float
- First as normal
- Moved as far left/right as possible
Absolute [Absolute & Fixed]
- Different position in render tree than the DOM tree
Box Layout Factors
- Box Type
- Box Dimension
- Positioning Scheme
- External Info. (img size, screen size, etc)
- Layered representation (third dimension)
Stacking Context - auto increment of Z-index
But, Manual Override is always there...
Painting
Global
or
Incremental
Dirty region --> OS invokes Paint
Paint Hierarchy
- BG Color
- BG Image
- Border
- Children
- Outline
Dynamics & Associated Cost
Painters are minimalist
- Change in element color
- Change in element position
- Layout and repaint on the element, its children and its affected siblings
- Adding a new DOM element
- Layout and repaint of the Node
- Increase in Font Size
- Invalidation of cache, relayout & repaint of entire tree
Javascript
Java === Javascript?
Ok, then answer this -
What is the difference between "Scripting" language and regular "Programming" language?
Answer lies in the use of the language
Its the mental thing...
Datatypes in Javascript
Simple/Primitive/Immutable Data Types
Number
String
Boolean
Undefined
Null
Complex/Fundamental/Mutable Data Type
Object
Object = list of unordered key value pairs
Properties & Methods
Functions are first class Objects!
2 ways of creating objects
Object Literal
var player = {"name":"Messi", "jersey":10, skill:"ok"};
Object Constructor
var player = new Object();
player.name = "Messi";
player.jersey = 10;
player.skill = "ok";
But, this is only for quick & dirty coding.
Use Constructor Pattern or Prototypal Pattern for real world problems.
Prototype?
Javascript functions have a prototype property
- empty by default
- non enumerable
- used to implement inheritance
- __proto__ as pseudo accessor
var myFoo = new foo();
myFoo.bar();
=> call the bar function of the prototype of foo with this = myFoo
Javascript Objects have a prototype attribute
- denotes its parent
var myFoo = new foo();
=> myFoo.prototype is assigned the foo.prototype
Scope
Local Scope vs Global Scope
Global => Init before declare
Local => Function Scope
var foo = {}
No Block Scope
Local Variable Prio > Global Variable Prio
Variable declaration are hoisted
Hence, Always declare local variables at the top
Closure
"2 Edge sword"
3 Closure scope chains:
- Inner variables
- variables in outer function
- Global variables
Closure has access to outer function's variables even after outer function returns
Closure stores references of outer function's variables and not the values
CallBack Pattern
"Passing function definition as argument to another function"
$("#btn").click(function(){...});
$("#btn").click(clickHandler);
Anonymous callback functions can be accessed via arguments object
passed callback function retains closure in receiving function
Check for callback type before executing it
if(typeof callback === "function"){...}
But what is the context (this) of the callback execution?
Apply, Call, Bind
"Liberates from uncertainties of this"
Apply & Call takes first argument as this within the callback
Difference?
callback.call(scopeObject, arg1, arg2);
callback.apply(scopeObject, [arg1, arg2]);
Bind also explicitly sets this
except that it returns a function
callback.bind(scopeObject, args...)();
What is currying and composing functions?
Javascript
Javascript is OO?
* Objects - Attributes & Methods
* Object can contain other Objects
* Constructor ~ Class
* Prototype oriented inheritance
* Capable of inheritance & aggregation
* Private members too!
- vars & params of Contructor
OOP in Javascript
Everything is Object in Javascript
Code Conventions
* Indent (Auto)
* Meaningful Comment
* Line Length <= 80
* Strict mode
- declare all vars/functions before use
- Never use Global Variables
- Close each statement
* Use names empathetically
* Use Blanks and empty lines generously
* Use {} instead of new Object()
* Use [] instead of new Array()
* eval is evil
JSON @ JS
myObject = JSON.parse(JSONText, reviver);
Deserialize
JSONText = JSON.stringify(myObject, replacer);
Serialize
Cyclical data structures?
Did You Know?
You can provide your own toJSON() implementation
WebWorkers
Can do XHR
Can load more scripts
Can setTimeout/clearTimeout
Can setInterval/clearInterval
can spawn more WebWorkers
Cannot access DOM
Cannot access Window
Cannot access Document
Cannot access Parent
WebWorkers
Run JS code in separate thread
Create WebWorker -
myWebWorker = new worker('heavyComputation.js');
Start WebWorker -
myWebWorker.postMessage(myJSONInput,[ArrayBuffer]);
{Not until the file is downloaded & executed}
Message event for communication
Pass by "Value"??
Or Transferable Objects - Zero Copy - Context Switch
Error Handling
"With Power Comes Great Responsibility"
What happens when there is a script error?
Try..Catch..Finally
If..Else..Throw
Window.onerror()
What if global error handler throws an error?
Learn the difference between -
== & ===
null & undefined
Quiz
null == undefined?
0 == false?
1 == "1"?
+0 === -0?
NaN == NaN?
AJAX
Asynchronous Javascript & XML
XMLHttpRequest
xhr = new XMLHttpRequest();
xhr.open(method, serviceUri, isAsyncBoolean);
xhr.setRequestHeader(param,value);
xhr.send(requestCotent);
xhr.responseText(); //synch
xhr.onReadyStateChange = callback(); //Asynch
Keep in mind ContentType
Power of Self Executing Temp Function
Another Annoying Quiz
We know var kabir = {"count":2}, But, what about var kabir = {2:"count"}?
Can I delete a property? delete kabir.count?
a = 10;
var myObject = {
a:20,
doAfter1Sec: function(){setTimeOut(function(){console.log(a);},1000);}
}
myObject.doAfter1sec();what is the scope of this in SetTimeOut?
var genericName;
function genericName(){
genericName = "Hello World";
}
console.log(typeof genericName); What is priority of function, variable & assignment?
console.log(typeof myFunc);
var myFunc = function(){...} Function Expressions are declaration or assignment?
Another Annoying Quiz Continues
Function howMany(greatPeople){
var i;
var count = 0;
for(i=0;i<greatPeople.length;i++){
greatPeople[i]["count"] = function(){
return count + i;
}
}
return greatPeople;
}
var listOfGreatPeople = [{name:"Buddha",count:0},
{name:"Kabir",count:0},
{name:"Rajnikanth",count:0}];var howManyForGreatPeople = howMany(listOfGreatPeople);
console.log(howManyForGreatPeople[0]["count"]);
Annoying Quizzes just don't stop
Function howMany(greatPeople){
var i;
var count = 0;
for(i=0;i<greatPeople.length;i++){
greatPeople[i]["count"] = function(index){
return function(){
count + index;
}()
}(i);
}
return greatPeople;
}
var listOfGreatPeople = [{name:"Buddha",count:0},
{name:"Kabir",count:0},
{name:"Rajnikanth",count:0}];var howManyForGreatPeople = howMany(listOfGreatPeople);
console.log(howManyForGreatPeople[0]["count"]);