Javascript basics – Why should you learn javascript? – Once upon a time...



Javascript basics – Why should you learn javascript? – Once upon a time...

0 0


mawek.github.io


On Github mawek / mawek.github.io

Javascript basics

Marek Gerhart @ GoodData 2013

Agenda

  • History
  • Overview
  • Types
  • Prototypal inheritance
  • Execution model
  • Developer tools

Rozmysla som ako ponat tuto prezentaciu. nechcel som aby to bol len pouhy vycet vlastnosti alebo referencna prirucka. Ale ono sa to moc neda pri prezentacii tohto typu Tak som sa tu snazil zhrnut len tie zakladne rysy jazyka, ktore ho odlisuju od ostatnych jazykov, pripadne nejake veci ktore nie su az take intuitivne a zrejme na prvy pohlad.

Why should you learn javascript?

Javascript is not just for moving html elements around the page anymore

Ked som este robil v et netere, maintainoval som jeden eshop v ich CMS a obcas tam trebalo urobit aj nejaku upravu na UI - vacisnou to teda robili supportaci ale niekedy som sa tomu nevyhol dni ja.

Nenavidel som to - povazoval som to za manualnu pracu na ktorej nie je nic tvorive, proste trebalo prida par html elementov niekde, nejake dalsie css classy a obcas este niecim zahybat cez jQuery a nieco poanimovat. Trebalo to furt ladit pre rozne prehliadace a bola to taka spinava praca. Snazil som sa tomu vyhybat.

Aby bolo jasne - o html a css som vedel nutne minimum, vzdy som si vygooglil aky selektor mam pouzit a ake atributy do css vlastne patria.. Co sa tyka js tak to som nepoznal skoro vobec, skopiroval som co som nasiel na nete a ono to nejako fungovalo. Isiel som na to skor intuitivne.

Web is the future - everything is moving to web

V poslednom case ale zacal webovy svet zazivat revoluciu - zacalo sa pomerne dost rozpravat o html5, css3 - selektor sem selektor tam, rozne css transformacie, javascriptove kniznice, bootstrap, knockout, backbone, node, angular.. nemal som tucha ako tie veci funguju Islo to mimo mna ale nejako som registroval ze je okolo toho rozruch. Bolo toho pomerne dost a uvedomoval som si ze sa to uz neda ignorovat, ze to je pomerne velka vec.

Preto ked prisla konzola - CCC tak som si povedal ze to je skvela prilezitost ako sa do toho ponorit, ako sa naucit nieco nove - co je lepsie ako cisto novy projekt, pre 1-2 ludi..

Tak som do toho skocil ale bolo toho vela. Vobec som nevedel co kde je ale bol som hodeny rovno do vody - javascript, ember, handlebars, sass, mocha, karma, grunt, node,...

Don't think about javascript as of language - think about it as of web platform

Javascript ecosystem is rich and it's on rise

Javascriptovy svet je teraz na vzostupe, je tam ked bola java pred 10 rokmi. Js vyzera ako sracka jazyk ale nedajte sa oklamat, java tiez nie je ziadne terno. A najlepsie na jave nie je jazyk, ale JVM a cely ekosystem co okolo toho existuje. A presne to plati aj pre javascript - je to najrozsirenejsi jazyk, da sa s tym robit hafo veci, teraz to prenika aj do backendu a do toolingu a nejde to ignorovat

Once upon a time...

Remember Netscape?

  • netscape bol celkom progresivny a novatorsky (on zaviedol cookies, script tag, ...)
  • chcel poskytnut uzivatelom nejaku moznost interakcie
  • potreboval nejaku konkurencnu vyhodu oproti MS

Brendan Eich - the father

  • otec javascriptu
  • chcel napisat nieco ako Scheme ale ked si v Nescape uvedomili co to vlastne je tak povedali ze ee
  • tak napisal javascript co je taky mix:
    • java(lebo musel bolo to prave in) (syntax)
    • scheme - dialekt LISPu (lambda + loose typing)
    • self - vychadzal zo smalltalku (prototypal inheritance)
    • perl (regexp)

naming

  • Mocha
  • LiveScript
  • JavaScript
  • JsCript
  • ECMAScript
  • Js1.5/Js1.8
  • vyvojarsky nazov pre jazyk bol Mocha
  • po release sa to oficialne volalo LiveScript
  • sun a netscape pochopili ze ms je velmi silny a ze by nebolo odveci spojit sa
    • sun chcel aby netscape zabilo LiveScript a stavilo na javu, co sa ale nepacilo netscapu
    • padol navrh na premenovanie LiveScript-u na JavaScript - Sun vlastni trademark a Nestcape bude jediny kto ho moze pouzivat
    • 1995 - vychadza JavaScript
  • MS zistil ze JavaScript je vlastne celkom fajn, tak ho cely reverse engineering-oval (spolu aj s chybami) a dal ho do IE3 ako JScript (kvoli trademark issues)
  • Netscape sa zlakol ze MS si s tym bude robit co chce, tak si povedal ze to treba rychlo standardizovat
    • Nestacape to najprv skusil u W3c ale ti ich poslali do prdele, tak skusili ISO a dalsi organizacie ale seci ich odmietli
    • nakoniec pochodili u ECMA (european computer manufacturer association) - ale netscape si dal podmienku ze standard sa nesmie volat Javascript - iba netscape tomu tak moze hovorit
    • ECMA prislo s jazykom ECMAScript
    • v standardizacnej komisii bol aj MS, takze to nebola az taka velka vyhra, MS trval na povodnej verzii
  • ES3(1999) je najrozsirenejsia verzia
  • ES4(2009) nikdy nevysla - mala prilis siroky scope tak to zarizli
  • 2011 - vysiel JSON 'standard' (Douglas Crockford to niekde zavesil na net)
  • javascript 1.5 a 1.8 - to je len verzovanie mozily 1.5==ES3, 1.8 ma nonstandard language extensions

JavaScript is

  • high-level
  • dynamic
  • untyped
  • interpreted
  • suitable for OO and functional style
  • XXX

The Good parts

  • Lambdas
  • Dynamic objects
  • Loose typing
  • Prototypal inheritance
  • Single threaded execution model
  • Object literal (JSON)
  • js is fast
  • XXX

The Bad parts

  • Global variables
  • The most misunderstood language
  • No standard library
  • Semicolon insertions
  • No block scope
  • with/eval/typeof/null vs undefined
  • global variables
    • js has no linker, everything is grouped in global namespace
  • because language is simple, people don't try to understand it but they use it asap
    • then they use it the wrong way and they are angry with the language
  • js is fast, DOM is slow (and js is taking the blame many times unfairly)
  • standard library - XXX
  • semicolon - XXX
  • scope - XXX
  • with/eval,... - XXX
  • most of the bad parts can be avoided

Client-side vs server-side dichotomy

  • client side - ember/angular
    • maven for this is bower
    • web workers
  • server side - node
    • maven for serverside is npm
    • fiber, etc
    • i needed $.extend - jquery can be included but it's not the best way
    • use 'loadash' in grunt

Closer overview

No compilator - only interpreter

JS is interpreted. But some browsers do optimize code - i.e. chrome compiles js to native code

  • JIT

JSLint

  • for code analysis
    • global variable access
    • switch - default

Garbage collector

  • automatic memory management

Single threaded execution model

  • Javascript is executed in browser in single thread
  • No waiting, no locking...
  • no blocking
  • web workers - for intensive tasks so UI thread is not blocked
    • can't manipulate DOM
    • can't share state between themselves
    • communicate using events (simple strings sending etc)
  • node.js
    • fiber - only single fiber is active, not fair
    • thread-a-go-go - like web workers
  • one would think that this would make js slow but it's not true
    • thanks to non-blocking nature js is really fast + webworkers/fiber

No standard library - only pure javascript and environment

  • spec defines only minimal API for arrays, dates, regexp...
  • no equals, no copy,...
  • environment provides the rest - Window object in browser provides setTimeout(), alert() functions etc
    • node.js provides own objects

Language is case-sensitive

  • beware when using with HTML
  • HTML is case-insensitive, there can be 'onclick' attribute and 'onClick' is valid too
  • in javascript, the handler name has to be lowercase 'onclick' (also in XHTML)
  • programs are written using UNICODE

Many reserved words, only couple of them are in use (+ global variables)

  • reserved
    • break case catch continue debugger default delete do else false finally for function if in instanceof new nul return switch this throw true try typeof var void while with
  • reserved not in use
    • class const enum export extends import super
  • strict mode keywords
    • implements interface let package private protected public static yeld
  • ES3 reserved all java keywords
    • abstract boolean byte char class const double enum export extends final float godo implements import int interface long native package private protected public short statis cuper synchronized throws transient volatile
  • global variables
    • arguments Array Boolean Date decodeURI decodeURIComponent encode URI encode URIComponent Error eval EvalError Function Infinity isFinite isNaN JSOnMath NaN Number Object parseFloat parseInt RangeError ReferenceError RegExp String SyntaxError TypError undefined URIError

Optional semicolon

can be omited between lines and js will insert it itself

          var a;
          a
          =
          5
          console.log(a) // the same as var a; a=5; console.log(a)

          var a=b+c
          (d+g).toString() // js will search for function c(dg)

      
  • js will put semicolon at the end of the line if the next nonspace character (on the next line) cannot be interpreted as a continuation of the current statement
    • var a; \n a \n = \n 5 \n console.log(a) => var a; a=5; console.log(a)
    • var a=b+c \n (d+g).toString() // if no semicolon - js will search for function c(dg)
  • beware on return/continue/break - they don't check next line

Variables & scope

Identifiers and keys

  • [a-zA-Z_$][a-zA-Z_$0-9]
  • no dash etc
  • object properties
  • if using square bracket notation - everything is permitted

Variables

  • var keyword
  • untyped
  • perform conversion when necessary (beware - can be tricky)
  • multiple vars doesn't matter
  • you can assign value to undeclared property but then it goes to the global scope
    • es5 throws error in such case
  • if you declare global variable, you are actually defining property of global object
  • it you do it using var = the property is nonconfigurable, and can't be deleted

Hoisting

      function swap1(a,b){
        sum = a + b;

        var sum; // this will get hoisted

        return sum;
      }

      function swap2(a,b){
        sum = a + b;

        var sum = 0; // assignment doesn't get hoisted

        return sum; // return 0 always
      }
    
  • variables are visible before they are declared - hoisting
    • but assignments are not hoisted
    • that's the reason why vars should be on top
    • but it breaks locality of access
  • no if/while.. block scope

scope

  • function scope only
  • no block scope:(
  • scope chain
  • function scope only! - in the whole javascript, there is function scope only
  • function scope layering - nested functions
  • scope chain - variable resolution
  • if you declare global variable, you are actually defining property of global object
  • it you do it using var = the property is nonconfigurable, and can't be deleted
  • global scope - if you don't use var
  • object - it's not real scope per se

Types

Loose typing

There are no types from user point of view

  • but there are types. You can gat TypeError when can't convert etc.
    • ({a:5}).helloWorld()

Primitive types

  • number
  • string
  • boolean
  • null
  • undefined (kind of)

Object types

everything that is not a primitive type is an object

Boolean

  • true/false
  • falsy values
    • undefined/null
    • 0/-0
    • NaN
    • ''
  • truthy values
    • everything else (even empty array)

Number

  • 64-bit floating point IEEE-754 (java double)
  • no integer/double distinction
  • arithmetics don't raise error in case of overlow/underflow/division by zero
  • edge cases - Infinity/NaN
    • NaN != NaN (the only case where x!=x)
  • array indexing is performed with 32-bit integers
  • don't write number literal with leading zero, some implementations consider it as octal value
  • ES5 forbids octal literals explicitly
  • underflow occurs if value is close to zero = 0 is produced (or -0)
  • division by zero produces NaN
  • x != x // will be true if and only if x is NaN

String

  • no surprise - immutable, ordered sequence of characters
  • in ES3 string literals must be oneliner, ES5 permits line breaks
  • 16-bit values - each represent Unicode character
  • length is number of 16-bit values it contain
  • pi.length == 1
  • e.length == 2
  • if escape character precedes any other character, it is ignored
  • beware when using "' in html - choose one and use it

wrapper objects for primitives

      var a = 5;
      a.toString();

      /* define property on wrapper object
      * but it will be disposed after this statement
      */
      a.someProperty = 'someValue';
      console.log(a); // undefined
    
  • string/number/boolean

null

      typeof null === 'object' // WTF?
    

undefined

  • absence of property
  • unitialized value
  • it's global value, that can be set (in ES3)
      var obj = {x: 5, y: 3};
      obj.x === 5;
      obj.y === 3;

      delete obj.x; // return true
      obj.x === undefined; // x doesn't exist on obj anymore

      obj.y = undefined;
      obj.y === undefined; // y property is still there!

    
  • default function return value
  • array return value (for non existing)
  • its global value that can be set (in ES3)
    • in ES5 undefined is read-only value
    • typeof undefined // returns 'undefined'

null or undefined ?

  • null is the right choice most of the time
  • don't set undefined manually (use delete or so)

function

  • function is object
  • function is true value
      var fun1 = function(){alert('hello world');}

      function namedFunction(){alert('hello world');}
    
  • object with executable code
  • function are values - they can be passed around,...

Date

Let's do it java style: 0 - based months, 1 - based days.

RegExp (perl syntax)

      var pattern = /[a-z0-9]+/i; // define case-insensitive regexp
      pattern.test('hello world'); // true

      'abc123'.match(/[0-9]/g); // ['1', '2', '3']

    
  • perl regexp /asdf/gi

Exceptions

      alert('hello world!');

      try {
        throw new Error('forbidden');
      } catch (e) {
        if (e instanceof SomeException) { // yeah this is kind of dumb
          throw 403;
        } else if (e.name === 'AnotherError') {
          throw {description: 'something happened'}
        }
      } finally {
        throw 'FatalError'
      }
    

Global object

  • defined by environment
  • defines common variables, functions, constructors
  • variables: undefined, Infinity, NaN, Math, JSON
  • functions: isNan(), parseInt(), eval()
  • constructors: Date), RegExp(), String(), Object(), Array()
  • initial properties of the global object are not reserved words but they should be treated like they are

Objects

  • composite value
  • hash/dictionary/associative array
  • dynamic
  • prototypal inheritance
  • aggregates multiple values
  • (unordered)collection of properties - each has name and value
  • dynamic - properties can be added/deleted at runtime
  • it can inherit some properties from another object (its prototype) - hence prototypal inheritance

Define object using literal

      var obj = {
        name: 'Jozko',
        surname: 'Mrkvicka',

        wholeName: function(){
          return this.name + ' ' + this.surname;
        }
      }
    

Define object using constructor function

      function Person(name, surname){
        this.name =  name;
        this.surname = surname;

        this.wholeName = function(){
          return this.name + ' ' + this.surname;
        }
      }

      // don't forget new keyword!
      var jozko = new Person('Jozko', 'Mrkvicka');

    

Define object using Object.create()

      var obj = Object.create(Object.prototype, {prop: {value: 'asdf'}})
    
  • property descriptor

Define object using custom library like Ember.js

      var Person = Ember.Object.extend({
        name: null,
        surname: null,

        wholeName: function(){
          return this.get('name') + ' ' + this.get('surname');
        }.property('name', 'surname');
      });

      var jozko = Person.create({name: 'Jozko', surname: 'Mrkvicka'});
    

Object properties

  • dot/square bracket notation
  • property attributes (value, writable, enumerable, configurable)
  • accessor properties (getter/setters)
  • deleting property
  • for in loop
  • notation
    • dot - can't use reserved words, no dash, spaces
    • bracket - anythink, even expression, even empty string
  • property attributes can be modified in ES3
    • ES5 allows modification, among other cool stuff - freezing object
  • delete property
    • like setting to undefined, but the property removes from enumeration
  • for in loop
    • for (var p in p){}
      • is you set some property as undefined, it WILL show up
      • if you delete some proeprty it won't show up
    • iterate over object (enumerable) properties, and its prototype properties
    • user can filter what he caser about

Defining properties

      var obj = {
        a: 'aa'
      }

      obj.b = 'bbb'

      Object.defineProperty(obj, 'c', {
        value: 'ccc',
        enumerable: 'false',
        configurable: 'false',
      });

      obj.hasOwnProperty('c') == true;

    
  • property descriptor
    • ES3 - can't be changed
    • ES5 - can be chaned using Object.defineProperty
  • writable - whether property can be set
  • enumerable - whether the property is returned in for/in loop
  • configurable - whether property can be deleted and attributes altered

Arrays

  • array literal
  • untyped
  • dynamic
  • pop/push/shift
      var arr = [1,2,,,{a:'b'},];
      arr.push('hello world');
      arr.length === 6 // true
      arr.someProperty = 'value'; // define property on array

      var anotherArr = new Array(10); // define sparse array

    
  • sparse
  • typeof returns 'object'
  • trailing comma is permitted [1,2,3,]
  • empty values are treated as undefined [1,2,3,,,4,5,]
  • zero based, 32 bit index
  • distinguish between indices and properties
    • index is integer between - and 2^32-1 - update length when such key
    • if you use negative number, or string, it is converted to string and ttreated as poperty
    • also if you use string which is number, it works as index (conversion)
  • array like objects
    • string
    • arguments

Arrays

      typeof [1,2,3] === 'object' // WTF?
    

Functions

  • first class citizens
  • function are values
  • hoisting
  • invocation context (this)
  • lexical scoping (closures)
  • values - they can be passed around etc
  • arguments
    • if fewer - undefined
    • if more - access through argument
    • length attribute - arity of function
  • names are useful for stacktraces
  • variable declaration get hoisted, but their assignment don't
  • also function declaration get hoisted (the whole with body not just the name)
  • closures - XXX
  • toString- i.e. require.js uses this for dependency searching (it's searching for require('something') so it knows which dependencies to load asynchronously)

Function definition

  • function definition expression
    var a = function sth(){}
  • function statement (function declaration)
    function sth(){}
  • function definition expression can include name for the function
    • define function as part of larger expression
    • var a = function sth(){} // named function
    • (function(){alert('asdf');})(); // self invoking function expression
  • function declaration
    • function sth(){}
    • without var
    • only top level, no in if/loop

function definition expression

TODO example should work
      var someFunction = function(){

        alert(helloWorld()); // this works fine

        // this would fail
        // alert(helloWorldVariable());

        // helloWorld function get hoisted to the top, so it can be called from everywhere
        // helloWorldVariable get hoisted but it assignment don't
        var helloWorldVariable = function helloWorld(){
          return 'hello world';
        }

        // closure
        return function(){
          return a++;
        }
      }
    

Function invocation patterns

They differ in invocation context (this)

  • function
    alert('hello world')
  • method
    list.sum()
  • constructor
    var date = new Date
  • indirect (call/apply)
    list.sum.apply([1,2])
  • invocation context - this
    • not a variable
    • not assignable
    • not keyword
    • doesn't have scope
  • function
    • global this
    • ES 5 put undefined in this
  • method
    • this is the object
    • property of object
  • constructor
    • newly created this
  • indirect
    • call - expects own argument list
    • apply - expects array
  • bind(this)

Function as namespace - module pattern

      (function(){
        var obj={},
            privateVariable = 1;

        obj.publicFunction = function(){
          return privateVariable;
        }
        return obj;
      }());

    
  • the parenthesis are necessary for the compiler to know that this isn't function declaration statement, but function definition expression
  • module pattern
    • since there is no real private state support in js

Closure

      var fn = function(){
        var a = 1;
        return function(){
          return a++;
        }
      }

      clos = fn();
      clos(); // 1
      clos(); // 2
      clos(); // 3 ...
    
  • lexical scoping - so the functions must include also reference to the current scope chain (when defining)
  • this combination of function object and scope(variable bindings) in which function variables are resolved is called a closure
  • technically all functions are closures
    • it gets interested for nested functions that are invoked later
  • scope chain is list of objects - not stack of bindings - thats why nested function also includes current scope when defining - its not stack that gets revinded if outter function returns

Prototype inheritance

Object has prototypes. If property is not found in current object, search throught prototype chain for it.

  • js is class free
  • objects inherit of objects
  • delegation (differential inheritance)
  • object created by new Date() inherits data from Date prototype and Object prototype

Constructor pattern

      // this is set to new object
      function Rabbit(name, type) {
        this.name = name;

        // 'private' encapsulated property
        this.type = function(){
          return type;
        }
      }

      Rabbit.prototype = new Animal;

      // define functions in prototype
      Rabbit.prototype.jump = function() {
        this.canWalk = true;
      }

      Rabbit.LACO = new Rabbit('Laco');

      // don't forget new keyword
      var rabbit = new Rabbit('John')
    
  • only constructor have prototype attribute
  • object prototype doesn't have prototype
  • every object has associated prototype (assigned during construction time)
  • no need for parenthesis if no params are necessary
  • Rabbit.prototype expects object
  • Rabbit is function, not object!
  • no super support out of the box, no constructor chaining out of the box

Object.create()

      var obj = Object.create(Object.prototype, {x: {value: 5}})
    
  • Object.create()
    • first argument is prototype
    • second argument is stuff to add (beware it's property descriptors! not plane properties)

Object literal


      // obj.prototype is Object.prototype
      var obj = {a:5}
    

is object prototype of another object ?


      // the ES5 way
      object.isPrototypeOf(anotherObj)

      // the old way
      object instanceof SomeConstructor

    

Statements, operators

instanceof, typeof

  • instanceof
    • prototype chain
    • left operand is object, right is function
  • typeof
    • not really useful
    • undefined: 'undefined'
    • null: 'object'
    • true/false: 'boolean'
    • number/NaN: 'number'
    • text: 'string'
    • functoin: 'function'
    • object/array: 'object'

equality

  • == performs conversion
  • === strict equation (identity operator)
  • === does not perform conversion, so it also compares types
    • check type
    • check type, check null/undefined (null/undefined===null/undefined), check if they are primitives (besides NaN), check for reference eq
  • == conversion (toString, valueOf), comparing primitives
    • like === but instead of reference comparing, it convert values and compare primitives
  • none of these performs deep equals ( no nested properties equation,..)

other operators

perform conversions when necessary

  • toString()
  • valueOf()

debugger

serves as breakpoint if debugger is running

  • formally is part of ES5 but most browser supports it
  • doesn't start debugger itself

"use strict"

ES5 directive for strict code - indicates that strict code follows

  • defined at the begining of the function or at the start of the script
  • something like annotation
  • restrictions
    • with statement is forbidden
    • function this is not scoped to the global object
    • no two properties with same name in object literal
    • no octal number literals
    • eval/arguments as keywords

eval

evaluate some string as javascript code - don't use it

      eval('alert("hello world!");
    
  • evaluates in current context
  • this should be operator, not a function
    • can be assigned to another var, interpreter can't optimize it
  • it can clutters your global space

with

temporarily extend scope chain - don't use it

      var a = 'aa',
          obj = {x = 'xx'};

      with(obj){
        x === 'xx'; // search on object
        a === 'aa'; // search from 'outer' scope
        c = 'cc'; // yikes! global scope
      }

    
  • serves as shortcut, can be replaced with simple var
  • hard to optimize
  • only for reading/changing properties
  • new property can't be defined this way
  • no clear way of telling whether property was accessed on object or from outter space

Execution javascript in browser

Window - the environment

Window serves as global object which provides API and some useful objects(document,location...) and methods (alert, setTimeout,...)

Js is running in two modes

  • synchronous(loading) mode
  • asynchronous (event-handling) mode
  • in history, there was no API for traversing DOM
  • the only way JS could manipulate DOM was generating it using document.write()
  • so browser hits script tag, it pauses rendering and execution, downloads and executes script

Embeding javascript code in HTML

  • inline between pair of script tags
  • external file
  • directly in HTMl as some event handler
  • script tag
    • close tag is required
    • default value for type is text/javascript so it't not necessary to set it
    • language attribute is deprecated (language='javascript')
  • defer/async atribut
    • can't use document.write
    • defer - trigger downloading script but execute it after dom is loaded/parsed,.. execute scripts in order they trigger download
    • async - trigger downloading script and execute it as soon as possible
  • all javascripts share the same namespace and same global object
  • inline
    • the code should be in CData section - if code contains <& marks (these characters are interpreted as XML markup)
  • external file
    • behaves exactly as inlined script
    • if you use src attribute, content between tags is ignored
    • caching - using CDN
      • same origin policy doesn't apply here - js code can interact with code no matter where it was loaded from
  • same origin policy

Browser waterfall

  • browser creates document and it starts parsing html page - creating html elements, text nodes ,...
    • set document.readyState = 'loading'
  • if browser hit script tag without async/defer:
    • stop parsing page
    • download script
    • wait until it's downloaded
    • execute script (script can see its script tag and elements before)
    • continue parsing html page
  • if browser hit script tag with async/deffer
    • trigger downloading code but continue parsing and processing html page
    • async script is executed as soon as possible (when it is downloaded), it is executed synchronously
  • when document is parsed, set document.readyState='interactive'
    • defer scripts trigger wight now (trigger them in order they were downloaded)
  • if document is parsed, fire DOMContentLoaded event on document
    • that means, browser goes to async phase
    • some script may be still executing in this phase
  • document is parsed, some scripts and images may be still loading
  • when everything is loaded and executed, set document.readyState = 'complete'
  • fire load event on window
  • async phase

  • there is no specification where should be content visible (browser specific)

  • window.onload

    • fire when dom is loaded(also pictures are downloaded and everything), it's built-in javascript event
    • fire when DOM is ready, pictures, ,everything ..
  • document.ready
    • jQuery extension, fire before window.onload, when DOM is loaded(but images might not be loaded yet), shold be triggered ASAP
    • fire when DOM is ready to be manipulated

Developer tools

Back in old days

Use the alert Luke!

Behold develooper tools

  • on windows/linux use F12
  • on mac press these klingon keys: ⌘ ⌥ I

elements

DOM manipulation

  • CSS adjustments
    • see all applicable styles with filenames
    • enable/disable style
    • code completition
    • :hover (desn't work with tooltips)
  • inspect element
    • or use magnifier from toolbox
  • in console inspect($('#nejake_id')) - find element
  • $0 - selected element
  • $ - like jquery, if there is jquery, it replaces chrome $
    • $('li') - najde setky licka na stranke
    • $('li').text('asdf'), zmeni vsetky licka na strnake
    • filtering versus traversing
      • $('#some_id ul li') - selection
      • $('#some_id ul').find('li') - selection with traversal (find) - it's faster this way
    • traversal over selection - performance boost is debatable (only first, last stuff)
    • resp mal by som pouzivat klasicke css selectory a nie jquery pseudo selectory (:radio,:eq, :checkbox)

resources

Cookies/localstorage,...

network

inspect network communication

  • see request, response, methods, headers
    • 304 - not modified, cache used
    • use SHIFT + REFRESH to hard refresh
  • waterfall
    • color by type
      • blue - html
      • orange - js
      • green - css
      • purple - images
    • blue line - firing dom.loaded (browser has parsed html file but some images still can be loading)
    • red line - firing load event (everything is downloaded)
    • show latency

sources

Browse through js/css/html files

  • save after many modifications (right click and save)
  • history
  • pretty print {}

profiler + timeline

profile css/javascript code

console

using for logging, debugging, pause on exception

  • open with escape key
  • autocompletition
  • breakpoint
  • console.log(info)
  • console.error(some_error)
  • console.log(someObj) // tree like structure

Useful resources

Q&A