1.  


  2. AngularJS: differences between service/factory/provide

    When starting with AngularJS, it’s important to realize the difference angular components: service, factory, provider, and value.

    This post on stackoverflow, which was born from this post in angular mailing list, explains the a great depth the difference between those notions including examples from Misko.

     


  3. Mobile Device Emulation with Chrome Dev Tools

    So, Google IO/14 is over. One of its main themes in web sphere was mobile. Mobile first. It’s growing. 1/3 of web sites visitors come from there. 

    Google pushes web platform and mobile forward by introducing polymer, web components, service workers, caring about mobile performance. One of the talks was devoted to the handy new feature that landed in Chrome Canary day before IO14 started - Device Emulation Mode. To be fare, Canary already had it placed in console drawers in dev tool but now it became very interactive.

    This article describes capabilities that the device emulation mode provides. Please note, this feature is available in Chrome Canary for now.

    Start

    For a start, open dev tool in Canary, and next to the Elements tab, you will notice the mobile icon.

    image

    This will trigger the emulation mode of the currently opened page.

    image

    Pay attention to the yellow line above the page itself. It will ask you to reload the page.

    There are two aspects that you can notice immediately: you simply resize the viewport and see how your website adapts to it, and the default emulation of touch events.

    Device Settings

    Top left corner, in orange, contains device settings. You can choose different type of devices that you’d like to test. List is pretty impressive. It has more than 50!!! different types of devices of popular vendors (Apple, HTC, Google, Samsung, etc.)

    image

    You can also set the width, height and rotation of the device, as well as its device pixel ratio to test your images on high dpi screens. The fit flag allows you to see the website either in full size or scaled to fit your screen.

    Media Queries

    Under the device settings part you can notice the media queries bars. To open them, click on the bars icon in the top left corner. What you will see is bars that correspond to the different media queries in your css. 

    image

    By clicking on one of them, your website will immediately rescale. And if you make a right click on any bar, you can navigate to its css resource.

    image

    Network

    On the right from the device settings panel, in blue, i can notice another one - network. This panel would allow you to choose the desired connection to test on whether it’s a wifi, 3G or even offline.

    image

    More

    On the right, far away from the network, you might notice three dot. 

    image

    If you click on them, dev tool will open the emulation draw where you can configure even more options.

    image

    For example, you can set the parameters of difference sensors. Set a latitude and longitude of geolocation or set angles for accelerometer.

     


  4. Mocking requireJS dependencies is a vital capability for proper unit tests. There are many solutions like Squire, Isolate, and testr that allows to do that. 

    But none of them works properly in Karma test runner. Mocker, using different contexts of requirejs, allows to mock dependencies of a module under testing.

     


  5. Note on static analysis of JavaScript

    This note is born due to the sentence that Igor Minar mentioned in JavaScript Jabber podcast episode on AngularJS. Here’s the whole passage.

    At Google, a lot of the code in JavaScript is statically analyzed using the Closure Compiler. And almost all JavaScript code is annotated using type annotations that come from the closure extension to JavaScript. I don’t know how to correctly describe it. So, Closure just uses common blocks to define what type an article or thing is. And you can describe interfaces in this way just like you would in a static language. And then the Closure Compiler can actually force that you’re passing the right type into the right function. And using this information, not only can it give you validation of your code or provide some feedback on correctness of your code, but it also can improve the minification capabilities. Because once the compiler knows about the structure of the code, it can change the structure of the code in a way that no other minifier can.

    So, what do is it give us? Besides the minification capabilities, the annotation and enforcement of types mainly influences on performance. If we don’t mess up types of JavaScript data structures (e.g don’t put numbers into array of strings), most of JS engines (V8, SpiderMonkey) know how to optimize them. This leads to better performance.

     


  6. Together with this, it’s totally worth to listen to JavaScript Jabber podcast episode about Hypermedia API.

     


  7. Notes on Website Performance Optimization Udacity course

    Lesson 0

    1. The DOM construction happens over the time in the following manner: html string -> tokens -> html nodes -> DOM.
    2. In dev tool timeline hit cmd+shift+r to will trigger browser hard reload of the page AND record the whole loading process in the timeline.

    Lesson 1 - The critical render path

    1. CSS properties are cascade down to its children.
    2. Simple CSS rules are parsed faster.
    3. Hit right click on time line to load or save it.
    4. Recalculate style (purple in timeline) is in charge of building CSSOM.
    5. Render tree represents only visible node, meaning head tag or nodes with display:none are not its’ parts.
    6. Layout step is calculating the position and dimensions of visible DOM node.
    7. Viewport meta tag sets the width property for css. Otherwise browser default viewport with is 980px.
    8. Batch updates to avoid multiple layouts.

    Lesson 2 - Optimizing CPR

    1. Separate media styles into different files and media attribute to link tag, e.g. <link href=”…” media=”print”> to prevent rendering blocking.
    2. Add async attribute to the script tag to prevent the loading js from blocking the CRP.
    3. Always minify, compress, and cache.
     


  8.  


  9. Composing Discrete Events with RxJS

    DOM events are very rich but badly composable. If we need a discrete conceptual move event, it would demand subscription to 3 DOM events: mousedown, mousemove, and mouseup.
    Below in the code in vanilla JavaScript.

    var moveEvent = {};
    
    function mouseDownHandler(ev) {
      document.addEventListener('mousemove', mouseMoveHandler, false);
      moveEvent.start = {
        x: ev.clientX,
        y: ev.clientY
      };
    }
    
    function mouseMoveHandler() {
      document.addEventListener('mouseup', mouseUpHandler, false);
    }
    
    function mouseUpHandler(ev) {
      moveEvent.target = ev.target;
      moveEvent.stop = {
        x: ev.clientX,
        y: ev.clientY
      };	
      document.removeEventListener('mousemove', mouseMoveHandler);
      document.removeEventListener('mouseup', mouseUpHandler);
      moveHandler(moveEvent);
    }
    
    function moveHandler(ev) {
      var body = document.querySelector('body');
      body.innerHTML = 'Start: x = ' + ev.start.x + ', y = ' + ev.start.y + '; Stop: x = ' + ev.stop.x + ', y = ' + ev.stop.y;
    }
    
    document.addEventListener('mousedown', mouseDownHandler, false);
    

    Live example on JSBin

    On mousedown, we register a listener to mousemove, and in its handler subscribe to mouse up. Mousedown handler extracts the coordinates start, and the mouseup handler extract stop coordinates and removes event listeners.

    The code is not long or complex but not readable.

    RxJS implements the concepts of reactive programming. The main idea (in a nutshell) is working with streams using LINQ operators and schedulers. It has insane amount of methods that can be applied. The authors neatly divided it into categories.
    Below is the code example that is required to reach the same results but only with RxJS.

    var mouseDowns = Rx.Observable.fromEvent(document, 'mousedown');
    var mouseMoves = Rx.Observable.fromEvent(document, 'mousemove');
    var mouseUps = Rx.Observable.fromEvent(document, 'mouseup');
    
    var moves = mouseDowns.selectMany(function (md) {
      var start = {
        x: md.clientX,
        y: md.clientY
      };
      return mouseMoves.combineLatest(mouseUps, function (mm, mu) {
        var stop = {
          x: mu.clientX,
          y: mu.clientY
        };
        return {
          start: start,
          stop: stop
        };
      }).takeUntil(mouseUps);
    });
    
    moves.subscribe(function (res) {
      var body = document.querySelector('body');
      body.innerHTML = 'Start: x = ' + res.start.x + ', y = ' + res.start.y + '; Stop: x = ' + res.stop.x + ', y = ' + res.stop.y;
    });
        

    Live example on JSBin

    As you may notice, the code becomes more elegant and self-explanatory. We subscribe to mousedown event, extract the its coordinates, and then start listening to mousemove events till mouse up event have occurred. From last event we retrieve the coordinates of stop and return the resulting discrete move event.

    The concepts of RxJS are very powerful that allows us to do less with more.

     


  10. RxJS Resources

    RxJS is an awesome library parted by Microsoft from C# that enables reactive paradigm in javascript.

    The amount of learning resources is very limited and not easy to find. Below is the list of the most useful one.

    1. Getting Started
    2. Operators be Categories
    3. Examples’ Implementations
    4. RxJS for beginners - series of blog posts from Microsoft (14 parts)
     


  11. Apart of the dissertation of a guy who invented REST, this presentation with lot’s of text contains the best explanations if RESTful concepts.

     


  12. JS Engine Jungle

    By far, the best write up that I’ve ever met about JS engines, their history, challenges, progress and implementation insights. 3 parts.

    Part 1, Part 2, Part 3

     


  13. The second best explanations about O.o() after the spec itself

     


  14.  


  15. Implementing Undo/Redo in JavaScript

    Implementing undo.redo functionality is not very common task in the world of front-end development but if you need that, it’s a must have feature.

    Like any other problem, it has many solutions: naive and the proper one (usually, harder one). 

    The implementation, of course, we start from the research.

    TL;DR 
    There are two main approaches to implement the history: 1) save the whole state; 2) save by actions. The former is easier to implement but its action granularity is smaller (hard to compose actions). The latter one is harder: implement command interface, command design pattern, several stacks and memory managements from removed object, - but it’s a more robust solution.

    So, here’s a list of useful readings: