Web Development Fundamentals


Why you here?


Do you want to build "beautiful" websites?

 Not happening 

Do you want to learn UI5 and Fiori?

 Not happening 

Do you want to master SPA design principles?

 Not happening 

Are you looking for the absolute guide to responsive UI?

 Not happening 



Before we start


HTML
is for Views

CSS
is for decoration

Javascript
is for behavior

A massive community for any help!

Philosophy





Why do you think Web technologies gained so much popularity?




Agenda


Brief intro to - 

Browser

Javascript

What next?



And loads of gas...

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


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?


Rendering Engine Flow




QUIZ Time


HTML === XML?
  • True
  • False

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


    1. Browser Declaration
    2. User Normal Declaration
    3. Author Normal Declaration
    4. Author Important Declaration
    5. 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]

    • As per box type
  • 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

          1. Box Type
          2. Box Dimension
          3. Positioning Scheme
          4. External Info. (img size, screen size, etc)
          5. 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

                  1. BG Color
                  2. BG Image
                  3. Border
                  4. Children
                  5. Outline

    Dynamics & Associated Cost

    Painters are minimalist

      • Change in element color 
        • Only repaint the element
      • 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




     

    Brief History of HTML...

          1. Tim Berners-Lee [1991]
          2. CSS + JS - [1996]
          3. HTML4 - CSS2 [1997 - 2000]
          4. Tableless + AJAX [2002 - 2005]
          5. HTML5 + CSS3 [2009]



    New Semantics


    <!DOCTYPE HTML>

    <script src="webdevfunda.js"></script>
    <link href="webdevfunda.css"></link>
    <input type="{many new types}"/>

    Demo of some useful new stuff

    Graphics & Effects


    <Canvas/>
    <svg/>
    WebGL - h/w acc. 3D in browser

    Why u no play Quake in browser?

    MultiMedia



    <video/>
    <audio/>

    Offline & Storage




    Cookies only?


    Web Storage

    • Local Storage
     
      • Key/Value
      • Easy API - localStorage.
        • setItem()
        • getItem()
        • removeItem()
        • clear()
  • Session Storage
      • Only Session scope
      • Best for One-time-temp-download

    Indexed DB

    Similar to Relational DB
    Object Store
    Async (callbacks)
    versioned


    APIs
    - Open() [onsuccess/onerror]
    - createObjectStore()
    - createIndex()
    - transaction() [read/write]

    Application Cache


    Cache Web Apps for Offline use
    - HTML + JS + CSS
    Max - 5MB?

    Connectivity


    Web Sockets (chat anyone?)

    CSS3


    New Selectors

    CSS3: New Selectors


    CSS3

    And...

    Opacity
    Text Decoration
    Color properties
    Gradients
    Shadows
    Border Images
    Rounded Corners
    Animation, Transforms & Transitions

    Native


    D&D (Web + Desktop)
    Geolocation
    Cross Domain Messaging
    File System API
    Speech Recognition
    ...

    Javascript


    Java === Javascript?
    • True
    • False



    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?
    • true
    • false


    * 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"]);

    Large Applications Need Special Attention

    Responsive Design

    Separation of concern - Framework anyone?
    - Knockout
    - Backbone
    - Angular

    Universal Event Handling

    Maintainable/Extendable/Reusable




    Debugging

    Browser integrated Dev Tools

    - Breakpoint
    - Steps
    - Pause on Exception
    - Exception Stack Trace
    - Console
    - Live editing



    - debugger statement in Javascript

    Stages of Javascript Learning

    Stage 1: Use as you like

    • Frequents W3C School
    • Select + Manipulate + screw up
    • Event Handlers for each and every item
    • Loop everything twice - "just like that"
    • Love the ease of jQuery & forgets Javascript
    • Compare with favorite Java/C++

    Stages of Javascript Learning


    Stage 2: Use it right
    • Frequents Stackexchange
    • Understands Object, Prototype, Closure
    • Accepts that errors can occur 
    • Moreover, tries to handle exceptions
    • Starts appreciating how browsers work
    • Still secretly loves his programming lang

    Stages of Javascript Learning


    Stage 3: code for future
    • Frequents and Answers on stackexchange 
    • Understand real difference in devices
    • Writes for reuse and extensibility
    • Compares frameworks and libraries
    • Dreams of writing own framework someday

    Stages of Javascript learning


    Stage 4: Server-side and browser engine
    • Looks to code in Javascript everywhere
    • Node.js is first priority
    • Understands real differences in browser engine
    • Obsessed with performance & security

    Stages of Javascript Learning


    Stage 5: Ninja
    • Frequents Quora to answer philosophical queries
    • Feels part of a political movement for Javascript
    • Talks about ES6 - Harmony like it is Bible
    • Deep down understands that its a long way to go

    ES6 - Harmony

    Web Components
    Modules
    Arrows
    Classes
    Templates
    let + const
    Generators
    Map + Set
    Proxies
    Symbols
    Promises
    ...

    Awesome, you shall not forget to be



    Web Development Fundamentals

    By Rupam Bhattacharya