=

desalasworks presents:

a selection of works by steven de salas

DarklyLabs LaserWeb

Warning: Use of undefined constant archives - assumed 'archives' (this will throw an Error in a future version of PHP) in /home/desagquj/public_html/wp-content/themes/desalasworks.v1.6/archive.php on line 36

Warning: Use of undefined constant page - assumed 'page' (this will throw an Error in a future version of PHP) in /home/desagquj/public_html/wp-content/themes/desalasworks.v1.6/archive.php on line 36

Warning: A non-numeric value encountered in /home/desagquj/public_html/wp-content/themes/desalasworks.v1.6/archive.php on line 36

Warning: A non-numeric value encountered in /home/desagquj/public_html/wp-content/themes/desalasworks.v1.6/archive.php on line 36
class="post-2120 post type-post status-publish format-standard has-post-thumbnail hentry category-desktop-application category-iot category-ui tag-electron tag-javascript tag-react tag-redux tag-webgl tag-websockets">

Steven was a one-man team building on top of open source “LaserWeb” software, automating and simplifying complex user flows to bring laser cutting to the beginner user.

This project involved full SDLC, building a simple and easy-to-use JavaScript wizard interface for the Emblaser2 laser cutter & engraver, which went from design to delivery in 6 weeks.

A challenging and very enjoyable project using NodeJS, JavaScript (ES6), Electron (Win/OSX Desktop app), Embedded, Computer Numerical Control (CNC/GCODE), WebWorkers, USB serialport, Github, CI / build automation (Travis, Appveyor), CSS, DOM Events, Webpack, React, Redux, Socket IO, WebGL 3D.

 

Immutability in JavaScript, A Contrarian View

Warning: Use of undefined constant archives - assumed 'archives' (this will throw an Error in a future version of PHP) in /home/desagquj/public_html/wp-content/themes/desalasworks.v1.6/archive.php on line 36

Warning: Use of undefined constant page - assumed 'page' (this will throw an Error in a future version of PHP) in /home/desagquj/public_html/wp-content/themes/desalasworks.v1.6/archive.php on line 36

Warning: A non-numeric value encountered in /home/desagquj/public_html/wp-content/themes/desalasworks.v1.6/archive.php on line 36

Warning: A non-numeric value encountered in /home/desagquj/public_html/wp-content/themes/desalasworks.v1.6/archive.php on line 36
class="post-1929 dw-article type-dw-article status-publish hentry category-code category-ui tag-javascript tag-react tag-redux">

TL/DR: Immutability is more a fashion trend than a necessity in JavaScript. If you are using React it does provide a neat work-around to some confusing design choices in state management. However in most other situations it wont add enough value over the complexity it introduces, serving more to pad up a resume than to fulfill an actual client need.

I wrote this originally as a answer to a stack overflow question posted by someone who was as baffled by this JavaScript programming trend as I was.

Here is my answer to this topic, it is contrarian and may also be contentious, but bear in mind its not the only answer, its just my own point of view.

Why is immutability so important(or needed) in javascript?

Well, I’m glad you asked!

Some time ago a very talented guy called Dan Abramov wrote a javascript state management library called Redux which uses pure functions and immutability. He also made some really cool videos that made the idea really easy to understand (and sell).

The timing was perfect. The novelty of Angular was fading, and JavaScript world was ready to fixate on the latest thing that had the right degree of cool, and this library was not only innovative but slotted in perfectly with React which was being peddled by another Silicon Valley powerhouse.

Sad as it may be, fashions rule in the world of JavaScript. Now Abramov is being hailed as a demigod and all us mere mortals have to subject ourselves to the Dao of Immutability… Wether it makes sense or not.

What is wrong in mutating objects?

Nothing!

In fact programmers have been mutating objects for er… as long as there has been objects to mutate. 50+ years of application development in other words.

And why complicate things? When you have object cat and it dies, do you really need a second cat to track the change? Most people would just say cat.isDead = true and be done with it.

Doesn’t (mutating objects) make things simple?

YES! .. Of course it does!

Specially in JavaScript, which in practice is most useful used for rendering a view of some state that is maintained elsewhere (like in a database).

What if I have a new News object that has to be updated? … How do I achieve in this case? Delete the store & recreate it? Isn’t adding an object to the array a less expensive operation?

Well, you can go the traditional approach and update the News object, so your in-memory representation of that object changes (and the view displayed to the user, or so one would hope)…

Or alternatively…

You can try the sexy FP/Immutability approach and add your changes to the News object to an array tracking every historical change so you can then iterate through the array and figure out what the correct state representation should be (phew!).

I am trying to learn what’s right here. Please do enlighten me 🙂

Fashions come and go buddy. There are many ways to skin a cat.

I am sorry that you have to bear the confusion of a constantly changing set of programming paradigms. But hey, WELCOME TO THE CLUB!!

Now a couple of important points to remember with regards to Immutability, and you’ll get these thrown at you with the feverish intensity that only naivety can muster.

1) Immutability is awesome for avoiding race conditions in multi-threaded environments.

Multi-threaded environments (like C++, Java and C#) are guilty of the practice of locking objects when more than one thread wants to change them. This is bad for performance, but better than the alternative of data corruption. And yet not as good as making everything immutable (Lord praise Haskell!).

BUT ALAS! In JavaScript you always operate on a single thread. Even web workers (each runs inside a separate context). So since you can’t have a thread related race condition inside your execution context (all those lovely global variables and closures), the main point in favour of Immutability goes out the window.

(Having said that, there is an advantage to using pure functions in web workers, which is that you’ll have no expectations about fiddling with objects on the main thread.)

2) Immutability can (somehow) avoid race conditions in the state of your app.

And here is the real crux of the matter, most (React) developers will tell you that Immutability and FP can somehow work this magic that allows the state of your application to become predictable.

Of course this doesn’t mean that you can avoid race conditions in the database, to pull that one off you’d have to coordinate all users in all browsers, and for that you’d need a back-end push technology like WebSockets (more on this below) that will broadcast changes to everyone running the app.

Nor does it mean that there is some inherent problem in JavaScript where your application state needs immutability in order to become predictable, any developer that has been coding front-end applications before React would tell you this.

This rather confusing claim simply means that if you use React your application is prone to race conditions, but that immutability allows you to take that pain away. Why? Because React is special.. its been designed first and foremost as a highly optimised rendering library with state management subverted to that aim, and thus component state is managed via an asynchronous chain of events (aka “one-way data binding”) that optimize rendering but you have no control over and rely on you remembering not to mutate state directly

Given this context, its easy to see how the need for immutability has little to do with JavaScript and a lot to do with React: if have a bunch of inter-dependent changes in your spanking new application and no easy way to figure out what your state is currently at, you are going to get confused, and thus it makes perfect sense to use immutability to track every historical change.

3) Race conditions are categorically bad.

Well, they might be if you are using React. But they are rare if you pick up a different framework.

Besides, you normally have far bigger problems to deal with… Problems like dependency hell. Like a bloated code-base. Like your CSS not getting loaded. Like a slow build process or being stuck to a monolithic back-end that makes iterating almost impossible. Like inexperienced devs not understanding whats going on and making a mess of things.

You know. Reality. But hey, who cares about that?

4) Immutability makes use of Reference Types to reduce the performance impact of tracking every state change.

Because seriously, if you are going to copy stuff every time your state changes, you better make sure you are smart about it.

5) Immutability allows you to UNDO stuff.

Because er.. this is the number one feature your project manager is going to ask for, right?

6) Immutable state has lots of cool potential in combination with WebSockets

Last but not least, the accumulation of state deltas makes a pretty compelling case in combination with WebSockets, which allows for an easy consumption of state as a flow of immutable events

Once the penny drops on this concept (state being a flow of events — rather than a crude set of records representing the latest view), the immutable world becomes a magical place to inhabit. A land of event-sourced wonder and possibility that transcends time itself. And when done right this can definitely make real-time apps easier to accomplish, you just broadcast the flow of events to everyone interested so they can build their own representation of the present and write back their own changes into the communal flow.

But at some point you wake up and realise that all that wonder and magic do not come for free. Unlike your eager colleagues, your stakeholders (yea, the people who pay you) care little about philosophy or fashion and a lot about the money they pay to build a product they can sell. And the bottom line is that its harder to code for immutability and easier to break it, plus there is little point having an immutable front-end if you don’t have a back-end to support it. When (and if!) you finally convince your stakeholders that you should publish and consume events via a push techology like WebSockets, you find out what a pain it is to scale in production.

 


Now for some advice, should you choose to accept it.

A choice to write JavaScript using FP/Immutability is also a choice to make your application code-base larger, more complex and harder to manage. I would strongly argue for limiting this approach to your Redux reducers, unless you know what you are doing… And IF you are going to go ahead and use immutability regardless, then apply immutable state to your whole application stack, and not just the client-side, as you’re missing the real value of it otherwise.

Now, if you are fortunate enough to be able to make choices in your work, then try and use your wisdom (or not) and do what’s right by the person who is paying you. You can base this on your experience, on your gut, or whats going on around you (admittedly if everyone is using React/Redux then there a valid argument that it will be easier to find a resource to continue your work).. Alternatively, you can try either Resume Driven Development or Hype Driven Development approaches. They might be more your sort of thing.

In short, the thing to be said for immutability is that it will make you fashionable with your peers, at least until the next craze comes around, by which point you’ll be glad to move on.


And the reply!

Hello Steven, Yes. I had all these doubts when I considered immutable.js and redux. But, your answer is amazing! It adds lot of value and thanks for addressing every single point that I had doubts on. It’s so much more clear/better now even after working for months on immutable objects. – bozzmob

TrifleJS

Warning: Use of undefined constant archives - assumed 'archives' (this will throw an Error in a future version of PHP) in /home/desagquj/public_html/wp-content/themes/desalasworks.v1.6/archive.php on line 36

Warning: Use of undefined constant page - assumed 'page' (this will throw an Error in a future version of PHP) in /home/desagquj/public_html/wp-content/themes/desalasworks.v1.6/archive.php on line 36

Warning: A non-numeric value encountered in /home/desagquj/public_html/wp-content/themes/desalasworks.v1.6/archive.php on line 36

Warning: A non-numeric value encountered in /home/desagquj/public_html/wp-content/themes/desalasworks.v1.6/archive.php on line 36
class="post-1739 post type-post status-publish format-standard has-post-thumbnail hentry category-code category-ui tag-c tag-distributed-computing tag-github tag-javascript tag-net-framework tag-test-driven-development">

triflejs-org

AutoTrader UK

Warning: Use of undefined constant archives - assumed 'archives' (this will throw an Error in a future version of PHP) in /home/desagquj/public_html/wp-content/themes/desalasworks.v1.6/archive.php on line 36

Warning: Use of undefined constant page - assumed 'page' (this will throw an Error in a future version of PHP) in /home/desagquj/public_html/wp-content/themes/desalasworks.v1.6/archive.php on line 36

Warning: A non-numeric value encountered in /home/desagquj/public_html/wp-content/themes/desalasworks.v1.6/archive.php on line 36

Warning: A non-numeric value encountered in /home/desagquj/public_html/wp-content/themes/desalasworks.v1.6/archive.php on line 36
class="post-1723 post type-post status-publish format-standard hentry category-code category-ui category-websites tag-agile tag-backbone-js tag-html5 tag-jasmine tag-javascript tag-jquery tag-performance-optimization tag-test-driven-development">

This was a role working on Interface Development for Trader Media’s online marketplace with over 1 billion page impressions per month.

autotrader_main

I mainly focused on creating rich interfaces and user journeys with Event-driven and Object-Oriented JavaScript, DOM, HTML5, jQuery, AJAX, JSON and Backbone.js MVC framework continuously tested with Jasmine/Rhino.

autotrader_gallery

Our team used Agile development approach with Continuous Integration (CI), pair-programming and short development cycles based on Thoughtworks Extreme Programming (XP) model for Java/JUnit TDD projects.

autotrader_agile_dave

Dan Murphys Lucky 8

Warning: Use of undefined constant archives - assumed 'archives' (this will throw an Error in a future version of PHP) in /home/desagquj/public_html/wp-content/themes/desalasworks.v1.6/archive.php on line 36

Warning: Use of undefined constant page - assumed 'page' (this will throw an Error in a future version of PHP) in /home/desagquj/public_html/wp-content/themes/desalasworks.v1.6/archive.php on line 36

Warning: A non-numeric value encountered in /home/desagquj/public_html/wp-content/themes/desalasworks.v1.6/archive.php on line 36

Warning: A non-numeric value encountered in /home/desagquj/public_html/wp-content/themes/desalasworks.v1.6/archive.php on line 36
class="post-1658 post type-post status-publish format-standard hentry category-competitions category-ui category-websites tag-facebook tag-heroku tag-mysql tag-php">

This Facebook competition was run on Chinese New Year 2013, it was designed by RedJelly and hosted by me using Heroku.

dm_lucky_8_desktop

The competition uses the entrant’s date of birth to show their Chinese horoscope before entering the competition:

dm_lucky_8_desktop_dragon

It included access to the Facebook API for authentication and to obtain email and date of birth information from competition entrants.

dm_lucky_eight_dashboard

MBTA mTicket

Warning: Use of undefined constant archives - assumed 'archives' (this will throw an Error in a future version of PHP) in /home/desagquj/public_html/wp-content/themes/desalasworks.v1.6/archive.php on line 36

Warning: Use of undefined constant page - assumed 'page' (this will throw an Error in a future version of PHP) in /home/desagquj/public_html/wp-content/themes/desalasworks.v1.6/archive.php on line 36

Warning: A non-numeric value encountered in /home/desagquj/public_html/wp-content/themes/desalasworks.v1.6/archive.php on line 36

Warning: A non-numeric value encountered in /home/desagquj/public_html/wp-content/themes/desalasworks.v1.6/archive.php on line 36
class="post-1372 post type-post status-publish format-standard hentry category-mobile category-ui tag-agile tag-android tag-cordova tag-css3 tag-html5 tag-iphone tag-javascript tag-qunit tag-test-driven-development">

A 6 month cross-platform (iOS and Android) mobile app project for Masabi, a specialist mTicketing company based near London Bridge. The MBTA mTicket application was launched in the Android and iPhone app markets in November 2012, and was a complete success grossing $1 million of sold tickets in the Boston Rail network for the first ten weeks of operation.

MBTA mTicket in the Google Play store.

MBTA mTicket in the Google Play store.

Developing the Front End User Experience

The project focused on building the User Interface for the application, this was done as a HTML5 /JavaScript UI due to the inherent advantages in being able to share code across different platforms. During development, we regularly tested against Android, iOS, BlackBerry, Symbian WebOS and Windows Mobile.

MBTA mTicket Payment Walkthrough

The process for purchasing tickets is straight forward, no complicated steps or black magic.

To purchase a round trip ticket to/from Boston the steps are:

1) Click ‘Buy Tickets’
2) Choose a ‘From’ and ‘To’ Station from the list.
3) Choose a ‘Round Trip’ ticket
4) Choose an existing card (the app stores a payment key after the first time).
5) Enter the Card CVV

mbta.workflow.new1

6) Review your purchase
7) Press ‘Pay Now’
8) DONE!

mbta.workflow.new2

Once the transaction goes through, the ticket is loaded into the My Tickets section. You now have two round trips to Boston waiting for you.

These last few panels are a shot of your ticket. The rectangle at the top shows the current time, the time block moves back and forth, and the three blocks are multi-colored. The color scheme changes on a daily basis according to a scheme that the conductor knows. Once the ticket is used it changes into a grey scheme. The conductor when he approaches will generally glance at the screen, nod with a “thanks” and put a paper slip in the holder above your head. Done.

mbta.workflow.new3

MBTA mTicket in the News

These are some of the online articles that were published before and after launch:

Apr 23rd, 2012

MBTA and Masabi team up for first smartphone rail ticketing system in the US, launching in Boston this fall

Jul 12th, 2012

New York MTA announces smartphone-based ticketing trials aboard Metro-North Railroad


July 11, 2012

New Smartphone App Could Replace Railroad Tickets


Nov 12, 2012

MBTA & Masabi Launch US` First Smartphone Commuter Rail Ticketing System

Jul 11, 2012

Digital train tickets to replace paper for some NY commuters


November 27, 2012

mTicket: MBTA releases mobile ticketing app at South Station

December 04, 2012

mTicket: T reports $225,000 in mobile app ticket sales since November launch

January 15, 2013

mTicket sees $1 million in commuter line sales


November 21st, 2012

What Bostonians Are Thankful For

November 27th, 2012

Mobile Ticketing Coming to MBTA Boats & More Commuter Trains, Riders Can Purchase Monthly Passes


Customer Respose

The MBTA mTicketing app went on to become a huge success shortly after launch. Customers reported a ‘seamless experience’ with ‘great usability’, ‘very convenient’, ‘neat & efficient’ etc.

These are some of the responses the MBTA customers tweeted shortly after launch:

25 Techniques for Javascript Performance Optimization

Warning: Use of undefined constant archives - assumed 'archives' (this will throw an Error in a future version of PHP) in /home/desagquj/public_html/wp-content/themes/desalasworks.v1.6/archive.php on line 36

Warning: Use of undefined constant page - assumed 'page' (this will throw an Error in a future version of PHP) in /home/desagquj/public_html/wp-content/themes/desalasworks.v1.6/archive.php on line 36

Warning: A non-numeric value encountered in /home/desagquj/public_html/wp-content/themes/desalasworks.v1.6/archive.php on line 36

Warning: A non-numeric value encountered in /home/desagquj/public_html/wp-content/themes/desalasworks.v1.6/archive.php on line 36
class="post-1177 dw-article type-dw-article status-publish has-post-thumbnail hentry category-code category-ui tag-javascript tag-performance-optimization">

These are some the techniques I use for enhancing the performance of JavaScript, they have mostly been collected over various years of using the language to improve the interactivity of websites and web applications.

My thanks go out to Marco of zingzing.co.uk for reminding me of the importance of optimizing JavaScript, and for teaching me some of the techniques below.

Most of the techniques involve common sense once you have understood the underlying problem. I’ve categorised them into 5 broad categories, each with an underlying problem and solution as follows:

1. Avoid interaction with host objects

Watch out for these guys. Repeated interaction with them will kill your performance.

THE PROBLEM:

Native JavaScript is compiled into machine code by most scripting engines offering incredible performance boost, however interaction with host (browser) objects outside the javascript native environment raises unpredictability and considerable performance lag, particularly when dealing with screen-rendered DOM objects or objects which cause Disk I/O (such as WebSQL).

THE SOLUTION:

You can’t really get away from them, but keep your interaction with host objects to an absolute minimum.

THE TECHNIQUES:

  1. Use CSS classes instead of JavaScript for DOM animation.

    Its a good habit to try an implement any animation (or DOM interaction) with CSS if you can get away with it. CSS3 Transitions have been around for a while now, so there are few excuses not to use them. You can even use a polyfill if you are worried about older browsers. Think also of hover menus using the :hover pseudo-class, or styling and display of elements using @keyframes, :before and :after, this is because unlike JavaScript, CSS solutions are heavily optimized by the browser, often down to the level of using the GPU for extra processing power.

    I realize this might sound like irony (if you want to optimize JavaScript – avoid using it for animation), but the reality is that this technique is executed from within your JavaScript code, it just involves putting more effort on the CSS classes.

  2. Use fast DOM traversal with document.getElementById().

    Given the availability of jQuery, it is now easier than ever to produce highly specific selectors based on a combination of tag names, classes and CSS3. You need to be aware that this approach involves several iterations while jQuery loops thorough each subset of DOM elements and tries to find a match. You can improve DOM traversal speeds by picking nodes by ID.

    // jQuery will need to iterate many times until it finds the right element
    var button = jQuery('body div.dialog > div.close-button:nth-child(2)')[0];
    
    // A far more optimized way is to skip jQuery altogether.
    var button = document.getElementById('dialog-close-button');
    
    // But if you need to use jQuery you can do it this way.
    var button = jQuery('#dialog-close-button')[0];
    
  3. Store pointer references to in-browser objects.

    Use this technique to reduce DOM traversal trips by storing references to browser objects during instantiation for later usage. For example, if you are not expecting your DOM to change you should store a reference to DOM or jQuery objects you are going to use when your page is created; if you are building a DOM structure such as a dialog window, make sure you store a few handy reference to DOM objects inside it during instantiation, so you dont need to find the same DOM object over an over again when a user clicks on something or drags the dialog window.

    If you haven’t stored a reference to a DOM object, and you need to iterate inside a function, you can create a local variable containing a reference to that DOM object, this will considerably speed up the iteration as the local variable is stored in the most accessible part of the stack.

  4. Keep your HTML super-lean (get rid of all those useless DIV and SPAN tags)

    This is extremely important, the time needed to query and modify DOM is directly proportional the the amount and complexity of HTML that needs to be rendered.

    Using half the amount of HTML will roughly double the DOM speed, and since DOM creates the greatest performance drag on any complex JavaScript app, this can produce a considerable improvement. See ‘Reduce Number of DOM Elements’ guidance in Yahoo YSlow.

  5. Batch your DOM changes, especially when updating styles.

    When making calls to modify DOM make sure you batch them up so as to avoid repeated screen rendering, for example when applying styling changes. The ideal approach here is to make many styling changes in one go by adding or removing a class, rather than apply each individual style separately. This is because every DOM change prompts the browser to re-render the whole UI using the boxing model. If you need to move an item across the page using X+Y coordinates, make sure that these two are applied at the same time rather than separately. See these examples in jQuery:

    // This will incurr 5 screen refreshes
    jQuery('#dialog-window').width(600).height(400).css('position': 'absolute')
                           .css('top', '200px').css('left', '200px');
    // Let jQuery handle the batching
    jQuery('#dialog-window').css({
         width: '600px',
         height: '400px',
         position: 'absolute',
         top: '200px',
         left: '200px'
    );
    // Or even better use a CSS class.
    jQuery('#dialog-window').addClass('mask-aligned-window');
  6. Build DOM separately before adding it to the page.

    As per the last item, every DOM update requires the whole screen to be refreshed, you can minimize the impact here by building DOM for your widget ‘off-line’ and then appending your DOM structure in one go.

  7. Use buffered DOM inside scrollable DIVs.

    This is an extension of the fourth point above (Keep HTML super-lean), you can use this technique to remove items from DOM that are not being visually rendered on screen, such as the area outside the viewport of a scrollable DIV, and append the nodes again when they are needed. This will reduce memory usage and DOM traversal speeds. Using this technique the guys at ExtJS have managed to produce an infinitely scrollable grid that doesn’t grind the browser down to a halt.

2. Manage and Actively reduce your Dependencies

Poorly managed JavaScript dependencies degrade user experience.

THE PROBLEM:

On-screen visual rendering and user experience is usually delayed while waiting for script dependencies load onto the browser. This is particularly bad for mobile users who have limited bandwidth capacity.

THE SOLUTION:

Actively manage and reduce dependency payload in your code.

THE TECHNIQUES: 

  1. Write code that reduces library dependencies to an absolute minimum.

    Use this approach to reduce the number of libraries your code requires to a minimum, ideally to none, thus creating an incredible boost to the loading times required for your page.

    You can reduce dependency on external libraries by making use of as much in-browser technology as you can, for example you can use document.getElementById('nodeId') instead of jQuery('#nodeId'), or document.getElementsByTagName('INPUT') instead of jQuery('INPUT') which will allow you to get rid of jQuery library dependency.

    If you need complex CSS selectors use Sizzle.js instead of jQuery, which is far more lightweight (4kb instead of 80kb+).

    Also, before adding any new library to the codebase, evaluate whether or you really need it. Perhaps you are just after 1 single feature in the whole library? If that’s the case then take the code apart and add the feature separately (but don’t forget to check the license and acknowledge author if necessary).

  2. Minimize and combine your code into modules.

    You can bundle distinct components of your application into combined *.js files and pass them through a javascript minimizer tool such as Google Closures or JsMin that gets rid of comments and whitespacing.

    The logic here is that a single minimized request for a 10Kb .js file completes faster than 10 requests for files that are 1-2kb each due to lower bandwidth usage and network latency.

  3. Use a post-load dependency manager for your libraries and modules.

    Much of your functionality will not need to be implemented until after the page loads. By using a dependency manager (such as RequireJS or Webpack) to load your scripts after the page has completed rendering you are giving the user a few extra seconds to familiarise themselves with the layout and options before them.

    Make sure that your dependency manager can ‘remember’ which dependencies have been loaded so you dont end up loading the same libraries twice for each module. See guidance for Pre-Loading and Post-loading in Yahoo YSLow, and be mindful about loading only what is necessary at each stage of the user journey.

  4. Maximise use of caching (eTags, .js files, etc).

    Cache is your best friend when it comes to loading pages faster. Try to maximise the use of cache by applying ETags liberally and putting all your javascript into files ending in *.js found in static URI locations (avoid dynamic Java/C# bundle generations ending with *.jsp and *.ashx) . This will tell the browser to use the locally cached copy of your scripts for any pages loaded after the initial one.

  5. Move scripts to the end of the page (not recommended).

    This is the lazy way of handling post-load dependencies, ideally you should implement a post-load dependency manager, but if you only have one or two scripts to load into the page you can add them at the very end of the HTML document where the browser will start loading them after the page is rendered, giving the user a few extra seconds of interaction.

3. Be disciplined with event binding

Be a ninja when using event handling.

THE PROBLEM:

Browser and custom event handlers are an incredible tool for improving user experience and reducing the depth of the call stack (so you avoid having a function calling a function which calls another function etc), but since they are hard to track due to their ‘hidden’ execution they can fire many times repeatedly and quickly get out of hand, causing performance degradation.

THE SOLUTION:

Be mindful and disciplined when creating event handlers. Get to know your weapons too, if you are using a framework then find out what’s going on underneath the hood.

THE TECHNIQUES:

  1. Use event binding but do it carefully.

    Event binding is great for creating responsive applications. However, it is important that you walk through the execution and various user journeys to make sure they are not firing multiple times or using up unnecessary resources behind the scenes. Comment your code well so they next guy (which may be you a few months down the line) can follow what’s going on and avoid this issue as well.

    If you are using AngularJS make sure you are getting rid of unnecessary ‘watchers’. These are background events that involve heavy processing and will slow down your app, particularly on mobile devices.

  2. Pay special attention event handlers that fire in quick succession (ie, ‘mousemove’).

    Browser events such as ‘mousemove’ and ‘resize’ are executed in quick succession up to several hundred times each second, this means that you need to ensure that an event handler bound to either of these events is coded optimally and can complete in less than 2-3 milliseconds.

    Any overhead greater than that will create a patchy user experience, specially in browsers such as IE that have poor rendering capabilities.

  3. Remember to unbind events when they are not needed.

    Unbinding events is almost as important as binding them. When you add a new event handler to your code make sure that you provide for it to stop firing when it is no longer needed, ideally using once-off execution constructs like jQuery.one() or coding in the unbind behaviour at that point. This will avoid you having the same handler bound multiple times degrading performance, or events firing when they are no longer needed, this often points to memory leaks in your app as pointed out by the React developers in this blog post.

    If you are using jQuery to bind and unbind events, make sure your selector points to a unique node, as a loose selector can create or remove more handlers than you intend to.

  4. Learn about event bubbling.

    If you are going to use event handlers, it is important that you understand how event bubbling propagates an event up the DOM tree to every ancestor node. You can use this knowledge to limit your dependency on event bubbling with approaches such as jQuery.live() and jQuery.delegate() that require full DOM traversal upon handling each event, or to  stop event bubbling for improved performance. See this great post on the subject.

  5. Use ‘mouseup’ instead of ‘click’.

    Remember that user interaction via the mouse or keyboard fires several events in a specific order. It is useful to remember the order in which these events fire so you can squeeze in your functionality before anything else gets handled, including native browser event handlers.

    A good example of this is to bind your functionality to the ‘mouseup’ event which fires before the ‘click’ event, this can produce a surprising performance boost in older browsers such as IE, making the difference between handling every interaction or missing some of the action if the user triggers clicks many times in succession.

4. Maximise the efficiency of your iterations

Performance becomes critical during long iterations.

THE PROBLEM:

Due to the processing time used, iterations are usually the first places where you can address performance flaws in an application.

THE SOLUTION:

Get rid of unnecessary loops and calls made inside loops.

THE TECHNIQUES:

  1. Harness the indexing power of JavaScript objects.

    Native JavaScript objects {} can be used as powerful Hashtable data structures with quick-lookup indexes to store references to other objects, acting similarly to the way database indexes work for speeding up search operations by preventing needless looping. 

    So why bother iterating to find something? You can simply use a plain object as an index (think of a phone-book) to get to your desired item quickly and efficiently. Here is an example as follows:

    var data = {
      index: {
                "joeb": {name: "joe", surname: "bloggs", age: 29 },
                "marys": {name: "mary", surname: "smith", age: 25 }
                // another 1000 records
             },
      get: function(username) {
                return this.index[username];
             }
    }
  2. Harness the power of array structures with push() and pop() and shift().

    Array push() pop() and shift() instructions have minimal processing overhead (20x that of object manipulation) due to being language constructs closely related to their low-level assembly language counterparts. In addition, using queue and stack data structures can help simplify your code logic and get rid of unnecessarily loops. See more on the topic in this article.

  3. Take advantage of reference types.

    JavaScript, much like other C-based languages, has both primitive and reference value types. Primitive types such as strings, booleans and integers are copied whenever they are passed into a new function, however reference types such as arrays, objects and dates are passed only as a light-weight reference.You can use this to get the most performance out of recursive functions, such as by passing a DOM node reference recursively to minimise DOM traversal, or by passing a reference parameter into a function that executes within an iteration. Also, remember that comparing object references is far more efficient than comparing strings.

  4. Use Array.prototype.join() for string concatenation.

    PLEASE NOTE: This article was first written in 2012 when string concatenation was a hazard to be aware of. However, these days most JavaScript engines have compilation tricks that have made this issue obsolete. The wording below is only really relevant for historical purposes.

    Joining strings using the plus sign (ie var ab = 'a' + 'b';) creates performance issues in IE when used within an iteration. This is because, like Java and C#, JavaScript uses unmutable strings.

    Basically, when you concatenate two strings, a third string is constructed for gathering the results with its own object instantiation logic and memory allocation. While other browsers have various compilation tricks around this, IE is particularly bad at it.A far better approach is to use an array for carrying out the donkey work, creating an array outside the loop, using push() to add items into to the array and then a join() to output the results. See this link for a more in-depth article on the subject.

5. Become friends with the JavaScript lexicon

Become a friend of the ECMA Standard and it make your code faster.

THE PROBLEM:

Due to its loosely-typed and free-for-all nature, JavaScript can be written using a very limited subset of lexical constructs with no discipline or controls applied to its use. Using simple function patterns repetitively often leads to poorly thought-out ‘spaghetti’ code that is inefficient in terms of resource use.

THE SOLUTION:

Learn when and how to apply the constructs of the ECMAScript language standard to maximise performance.

THE TECHNIQUES:

  1. Shorten the scope chain

    In JavaScript, whenever a function is executed, a set of first order variables are instantiated as part of that function. These include the immediate scope of a function (the this variable) with its own scope chain, the arguments of the function and all locally-declared variables.

    If you try and access a globally-declared variable or a closure further up the scope chain, it will take extra effort to traverse up the chain every level util the compiler can wire up the variable you are after. You can thus improve execution by reducing the depth of the call stack, and by only using the local scope (this), the arguments of the function, as well as locally declared variables. This article explains the matter further.

  2. Make use of ‘this’, by passing correct scope using ‘call’ and ‘apply’.

    This is particularly useful for writing asynchronous code using callbacks, however it also improves performance because you are not relying on global or closure variables held further up the scope chain. You can get the most out of the scope variable (this) by rewiring it using the special call() and apply() methods that are built into each function. See the example below:

    var Person = Object.create({
      init: function(name) {
         this.name = name;
      },
      do: function(callback) {
         callback.apply(this);
      }
    });
    var john = new Person('john');
    john.do(function() {
        alert(this.name); // 'john' gets alerted because we rewired 'this'.
    });
  3. Learn and use native functions and constructs.

    ECMAScript provides a whole host of native constructs that save you having to write your own algorithms or rely on host objects. Some examples include Math.floor(), Math.round(), (new Date()).getTime() for timestamps, String.prototype.match() and String.prototype.replace() for regexes, parseInt(n, radix) for changing numeral systems, === instead of == for faster type-based comparsion, instanceof for checking type up the hierarchy, & and | for bitwise comparisons. And the list goes on and on.

    Make sure you use all these instead of trying to work out your own algorithms as you will not only be reinventing the wheel but affecting performance.

  4. Use ‘switch’ instead of lengthy ‘if-then-else’ statements.

    This is because  ‘switch’ statements can be optimized more easily during compilation. There is an interesting article in O’Reily about using this approach with JavaScript.

 

Object-Oriented JavaScript Inheritance

Warning: Use of undefined constant archives - assumed 'archives' (this will throw an Error in a future version of PHP) in /home/desagquj/public_html/wp-content/themes/desalasworks.v1.6/archive.php on line 36

Warning: Use of undefined constant page - assumed 'page' (this will throw an Error in a future version of PHP) in /home/desagquj/public_html/wp-content/themes/desalasworks.v1.6/archive.php on line 36

Warning: A non-numeric value encountered in /home/desagquj/public_html/wp-content/themes/desalasworks.v1.6/archive.php on line 36

Warning: A non-numeric value encountered in /home/desagquj/public_html/wp-content/themes/desalasworks.v1.6/archive.php on line 36
class="post-995 dw-article type-dw-article status-publish has-post-thumbnail hentry category-code category-ui tag-javascript tag-object-orientation">

This is simple but crucial stuff in JavaScript. Its easy to forget how to do object-oriented inheritance from scratch when you are dealing with several JS frameworks and each of them has pre-built methods that support this functionality in a slightly different way.

JavaScript is a functional language that uses prototypal inheritance. That means you can use classical inheritance such as that supported by Java and C#, however you need to be disciplined about the way you write code and need do a couple of things every time you add a class to your type hierarchy.

When creating a new class, we are essentially creating a function and assigning a new instance of another function as the prototype. This is the basis of ‘prototypal’ inheritance, ie. if you are dealing with ‘Dog’ type that inherits from an ‘Animal’ class, the template for your dog is a newly created instance of animal.

For Example:

// Create a new class called 'Animal'
var Animal = function() {};

// Create an instance of the 'Animal'
var anAnimal = new Animal();

// Create a class called 'Dog'
var Dog = function() {};

// Assign the template
Dog.prototype = anAnimal;

// Instantiate the dog
var lassie = new Dog();

Abstracting inheritance

I’ve created a simple static method called ‘extend’ on the Object class. Most frameworks do this in one shape or another (ie ExtJS uses Ext.extend(), John Resig likes to use Class.extend() method, Mootools uses new Class(properties) approach etc).

A ‘static’ method means that only the ‘Object’ class template will have it, so we do not pass it over to our children through inheritance. See the following code:

// Create a static 'extends' method on the Object class
// This allows us to extend existing classes
// for classical object-oriented inheritance
Object.extend = function(superClass, definition) {
    var subClass = function() {};
    subClass.prototype = new superClass();
    for (var prop in definition) {
        subClass.prototype[prop] = definition[prop];
    }
    return subClass;
};

This allows us to simplify the process of using object-oriented inheritance by abstracting the prototype assignment into this separate function call.

// Create an 'Animal' class by extending
// the 'Object' class with our magic method
var Animal = Object.extend(Object, {
    move : function() {alert('moving...');}
});

// Create a 'Dog' class that extends 'Animal'
var Dog = Object.extend(Animal, {
    bark : function() {alert('woof');}
});

// Instantiate Lassie
var lassie = new Dog();

// She can move AND bark!
lassie.move();
lassie.bark();

Adding Constructors

But, we seem to have forgotten one thing. What about constructors?

JavaScript uses the function itself as the constructor for a new object. Thus, when we created the Animal object above we could have simply added some sample code to its constructor as follows:

// Assign the name of the animal when it gets instantiated
var Animal = new function(name) {
  this.name = name;
}

var lassie = new Animal('Lassie');
alert('My pets name is: ' + lassie.name);

Thus we can augment our class creation methodology using the same idea:

// Create a 'Subclass' with a constructor
var SubClass = Object.extend(SuperClass, {
    constructor: function(parameter) {
        this.x = parameter;
    },
    method1: function() {
        // ...
    }
});

// Instantiate it
var subClass = new SubClass('value');
alert(subClass.x);

In order to allow this kind of notation, we can modify our ‘extend’ method to take care of this special ‘constructor’ function. This is done as follows:

// Create a static 'extends' method on the Object class
// This allows us to extend existing classes
// for classical object-oriented inheritance
Object.extend = function(superClass, definition) {
    var subClass = function() {};
    // Our constructor becomes the 'subclass'
    if (definition.constructor !== Object)
        subClass = definition.constructor;
    subClass.prototype = new superClass();
    for (var prop in definition) {
    	if (prop != 'constructor')
            subClass.prototype[prop] = definition[prop];
    }
    return subClass;
};

And put it to use by writing minimal code that is meaningful to read and leaves the object-creation abstraction sitting behind the scenes:

// Create the 'Animal' class by extending
// the 'Object' class with our magic method
// this time using a constructor
var Animal = Object.extend(Object, {
    constructor: function(name) {
        this.name = name;
    },
    move: function() {
        alert('moving...');
    }
});

// Instantiate Lassie (as an animal)
var lassie = new Animal('Lassie');

// Now lassie has a name which is
// defined inside the object constructor
alert('My pets name is: ' + lassie.name);

Calling constructors through the inheritance chain.

Now we have come up against a small problem, our ‘Animal’ class can have a constructor, but its child class ‘Dog’ has no way to call this constructor so it can take advantage of the logic for instantiating all animals.

In order to do this we are going to add a special ‘superClass’ property to all of our classes automatically, then use the magic ‘call’ function to call this using the context of the dog instance (to put it in plain english, this will make each ‘Dog’ run the logic for an ‘Animal’).

Lets see, all together now:

// Create a static 'extends' method on the Object class
// This allows us to extend existing classes
// for classical object-oriented inheritance
Object.extend = function(superClass, definition) {
    var subClass = function() {};
    // Our constructor becomes the 'subclass'
    if (definition.constructor !== Object)
        subClass = definition.constructor;
    subClass.prototype = new superClass();
    for (var prop in definition) {
    	if (prop != 'constructor')
            subClass.prototype[prop] = definition[prop];
    }
    // Keep track of the parent class
    // so we can call its constructor too
    subClass.superClass = superClass;
    return subClass;
};

// Create the 'Animal' class by extending
// the 'Object' class with our magic method
// this time using a constructor
var Animal = Object.extend(Object, {
    constructor: function(name) {
        this.name = name;
    },
    move: function() {
        alert('moving...');
    }
});

// Create a 'Dog' class that inherits from it
var Dog = Object.extend(Animal, {
    constructor: function(name) {
        // Remember to call the super class constructor
        Dog.superClass.call(this, name);
    },
    bark: function() {
        alert('woof');
    }
});

// Instantiate Lassie
var lassie = new Dog('Lassie');

// She can move AND bark AND has a name!
lassie.move();
lassie.bark();
alert('My pets name is: ' + lassie.name);

Multiple inheritance using Interfaces

Now its possible to add support for multiple inheritance to our object creation syntax in Javascript. In single-inheritance object-oriented languages such as Java and C#, multiple inheritance (inheriting properties and methods from more than one class chain) is done using Interfaces.

The implementation is a bit more crude than in Java or C#, the reason why is because Javascript, unlike these languages, is not compiled so we cant throw compilation-time errors. This means that when we implement an interface we are limited to checking that the appropriate members are there at runtime and if not we through an error.

So, lets start first with our intended usage for Interfaces:

var SubClass = Object.extend(SuperClass, {
     method1: function() {
         alert('something');
     }
}).implement(Inteface1, Interface2 ...);

Going by this approach, we need to create a method ‘implement’ for every class, since in Javascript our classes are instances of the ‘Function’ object, this means adding this method to Function.prototype.

The code does start to be a bit hairy from this point, its important to point out that the context of this function call (ie this) is the class that we are testing for implementation of a particular interface.

Function.prototype.implement = function() {
    // Loop through each interface passed in and then check
    // that its members are implemented in the context object (this)
    for(var i = 0; i < arguments.length; i++) {
         var interf = arguments[i];
         // Is the interface a class type?
         if (interf.constructor === Object) {
             for (prop in interf) {
                 // Check methods and fields vs context object (this)
                 if (interf[prop].constructor === Function) {
                     if (!this.prototype[prop] ||
                          this.prototype[prop].constructor !== Function) {
                          throw new Error('Method [' + prop
                               + '] missing from class definition.');
                     }
                 } else {
                     if (this.prototype[prop] === undefined) {
                          throw new Error('Field [' + prop
                               + '] missing from class definition.');
                     }
                 }
             }
         }
    }
    // Remember to return the class being tested
    return this;
}

And there you have it! Its important to point out that this is one of many ways to abstract object-orientation in Javascript. There are different approaches, and as a programmer it helps to pick one you are more comfortable with. Personally, I like this approach because of its simplicity, readability, and ease of use:

// Create a 'Mammal' interface
var Mammal = {
    nurse: function() {}
};

// Create the 'Pet' interface
var Pet = {
    do: function(trick) {}
};

// Create a 'Dog' class that inherits from 'Animal'
// and implements the 'Mammal' and 'Pet' interfaces
var Dog = Object.extend(Animal, {
     constructor: function(name) {
          Dog.superClass.call(this, name);
     },
     bark: function() {
          alert('woof');
     },
     nurse: function(baby) {
          baby.food = 100;
     },
     do: function(trick) {
          alert(trick + 'ing...');
     }
}).implement(Mammal, Pet);

// Instantiate it
var lassie = new Dog('Lassie');
lassie.move();
lassie.bark();
lassie.nurse(new Dog('Baby'));
lassie.do('fetch');
alert('My pets name is: ' + lassie.name);

Markit Environmental Registry

Warning: Use of undefined constant archives - assumed 'archives' (this will throw an Error in a future version of PHP) in /home/desagquj/public_html/wp-content/themes/desalasworks.v1.6/archive.php on line 36

Warning: Use of undefined constant page - assumed 'page' (this will throw an Error in a future version of PHP) in /home/desagquj/public_html/wp-content/themes/desalasworks.v1.6/archive.php on line 36

Warning: A non-numeric value encountered in /home/desagquj/public_html/wp-content/themes/desalasworks.v1.6/archive.php on line 36

Warning: A non-numeric value encountered in /home/desagquj/public_html/wp-content/themes/desalasworks.v1.6/archive.php on line 36
class="post-334 post type-post status-publish format-standard has-post-thumbnail hentry category-ui category-web-applications tag-extjs tag-investment-banking tag-javascript tag-json tag-object-orientation tag-trading-platform">

The Markit Environmental Registry is a central repository for tracing the ownership of carbon credits anywhere in the world and is the 1st ranked registry in 2012 Environmental Finance’s survey.

Rich Application for Carbon Market Transactions

Development of a fully Object-Oriented Javascript interface using the latest version of the EXT JS framework, a fully featured AJAX and GUI widget library based on Yahoo UI.

This was a 6 month project going live in September 2010 as part of the Markit suite of environmental products. The Markit Environmental Registry is a central repository for tracing the ownership of carbon credits anywhere in the world and has helped Markit gain 1st place for ‘Best Registry Provider’ in 2012 Environmental Finance’s survey.

While the work was primarily focused on individual paid-for access, there is also a complimentary public view interface that allows non-users to query database directly (written in plain HTML for SEO optimization).

Registry Landing Page

Delivering Features with Optimal Usability

Deliverables include a fully-operating Graphic User Interface compatible with IE (6,7 and 8), Firefox (3.0 upwards), Chrome and Safari in the form of an 8,000 line JavaScript library with 43 compiled javascript classes using object-oriented inheritance for minimal code-repetition and Java nomenclature and namespace breakdown wherever possible (with a view to find a replacement Java programmer) .

AJAX Architecture

The end result is a rich interface for a data-driven web application, with look-and-feel similar to that of a desktop application like Excel or Outlook. The users of the registry can access the following features:

Advanced Dockable Components

Standardised components such as grids (for record lists) allow for easily building functionality with components that can be docked in tab panels or within a popup window. Base components provide key functionality, such as layout, ordering, paging and searching and can be extended depending on the requirements for each section of the application.

Advanced Dockable Components

Simplified Search Criteria

Search criteria is simplified and prioritised to hide items that are less relevant to the user. Searching requires minimal input from the user (usually mouse-scroll and click).

Simplified Search Criteria

Predictive Search

An AJAX favourite. The implementation within the Registry is done using DOM buffering (only the items displayed are being rendered in the browser) which allows for thousands of records to be quickly filtered down to those that fit relevant criteria in milliseconds.

Predictive Search

Context Menus (right mouse button)

Context menus are used for right-clicking on a piece of information to find out relevant actions that can be performed. This is ported from functionality found in desktop application such as Outlook or Excel.

Context Menus

Windowed Interface

Window “lightboxes” are used to display information about individual records. These are pop-ups rendered within the page as modal windows, which provide a high degree of responsiveness in the application and the look-and-feel of traditional desktop applications.

Windowed Interface

Server-Side Validation Messages

Intuitive and appealing server side validation messages (without needing to refresh the page). The fields a user has entered incorrectly are clearly highlighted and provide additional information when hovering above them.

Server Validation

Hierarchical Data Representation (expanding trees)

Data is presented hierarchically wherever relevant, for example a syndication “Basket” used for risk management, can be constructed to contain other items within in. The User Interface displays this as an expandable item, with other items within it.

Hierarchical Data Representation

Object-Oriented Inheritance

The interface is designed as a self-contained JavaScript class library with components (Classes) that inherit from each other. This is done to reduce code-duplication and make the software more manageable.

Object Inheritance

Environmental Registry in the News

Markit Environmental Registry named ‘Best Registry Provider
April 2012

 

Feedback on the Registry

Some of the feedback received on this project:

UserEli Goncalves (End User)
www.personalco2zero.com

13 Sep 2010 – Your new platform really became more practical. Congrats!

UserHelen Robinson (Founder)
www.markitenvironmental.com

20 Sep 2010 – You guys have done a wonderful job, thank you very much!

Pepsi Project Refresh

Warning: Use of undefined constant archives - assumed 'archives' (this will throw an Error in a future version of PHP) in /home/desagquj/public_html/wp-content/themes/desalasworks.v1.6/archive.php on line 36

Warning: Use of undefined constant page - assumed 'page' (this will throw an Error in a future version of PHP) in /home/desagquj/public_html/wp-content/themes/desalasworks.v1.6/archive.php on line 36

Warning: A non-numeric value encountered in /home/desagquj/public_html/wp-content/themes/desalasworks.v1.6/archive.php on line 36

Warning: A non-numeric value encountered in /home/desagquj/public_html/wp-content/themes/desalasworks.v1.6/archive.php on line 36
class="post-875 post type-post status-publish format-standard has-post-thumbnail hentry category-branding category-ui category-web-applications tag-agile tag-css3 tag-distributed-computing tag-dom tag-github tag-html5 tag-javascript tag-jquery tag-json tag-qunit">

A global-reach social media campaign for renown household brand. This project involved designing an interface for a competition mechanics application with some of the latest technologies such as RESTful AJAX, jQuery, jQT, Qunit, HTML5, GitHub, Ruby on Rails all delivered over Amazon’s E2 Cloud delivery network.

The Pepsi Project Refresh

Pepsi Project Refresh – Global Competition Campaign

The Pepsi Refresh Project is an international social-media campaign aimed principally at teenagers and young adults, Pepsi’s main consumer base.

The project involved working with other skilled interface developers to customize the GUI and enhance an existing competition-mechanics platform (supplied by Global Dawn, a London-based specialist software developer) to provide Pepsi with the ability to create and judge competition rounds using bespoke rules, giving users have the ability to upload content and rate other user’s content all using Pepsi’s familiar blue branding.

Rich User Interface Technology

The principal technology stack of the project was RESTful AJAX over Ruby on Rails, this meant a highly-responsive UI that required minimal refreshing of the browser’s window. The main frameworks used for this were jQuery and QUnit(for unit testing).

Compatibility requirements meant unit-testing across various browser platforms.

A distributed team across several geographical areas meant using a robust and well-known Source Control and Bug-tracking platforms, GitHub, the platform of choice for many open-source projects was used for this purpose. Jira, another excellent solution provided by Atlassian, was used mostly for bug-tracking and task management.

Amazon Cloud

Various Technologies used for the Project

In order to improve high-volume delivery across all international location, the project used Amazons EC2 CloudDelivery Network.

Global Release

At then end of the project, the platform was localised and released across various international site. Russia and Italy being the first two participants in the competition.

Russian Site: platform was localised and delivered across various International Sites.

User-Generated Content

The key to the low-maintenance requirements of the competition is that users generate their own content. They upload videos and images, and they get to vote on videos and images provided by other users. According to Global Dawn’s 1-9-90 competition technology, some users tend to provide the majority of traffic and content in a site, hence these users are rewarded with ‘points’ to spend across the site as they see fit.

Italian Site: Users upload their own content and vote on other people’s content.

Competition mechanics are designed by brand managers (Pepsi in this case), they choose different parameters such as the duration of the competition, number of stages etc.