JavaScript Articles

Sort by:


  1. Porting to Emscripten

    Emscripten is an open-source compiler that compiles C/C++ source code into the highly optimizable asm.js subset of JavaScript. This enables running programs originally written for desktop environments in a web browser.

    Porting your game to Emscripten offers several benefits. Most importantly it enables reaching a far wider potential user base. Emscripten games work on any modern web browser. There is no need for installers or setups – the user just opens a web page. Local storage of game data in browser cache means the game only needs to be re-downloaded after updates. If you implement a cloud based user data storage system users can continue their gameplay seamlessly on any computer with a browser.

    More info is available in:

    While Emscripten support for portable C/C++ code is very good there are some things that need to be taken into consideration. We will take a look at those in this article.

    Part 1: Preparation

    Is porting my game to Emscripten even feasible? If it is, how easy will it be? First consider the following restrictions imposed by Emscripten:

    • No closed-source third-party libraries
    • No threads

    Then, already having some of the following:

    • Using SDL2 and OpenGL ES 2.0 for graphics
    • Using SDL2 or OpenAL for audio
    • Existing multiplatform support

    will make the porting task easier. We’ll next look into each of these points more closely.

    First things to check

    If you’re using any third-party libraries for which you don’t have the source code you’re pretty much out of luck. You’ll have to rewrite your code not to use them.

    Heavy use of threads is also going to be a problem since Emscripten doesn’t currently support them. There are web workers but they’re not the same thing as threads on other platforms since there’s no shared memory. So you’ll have to disable multithreading.


    Before even touching Emscripten there are things you can do in your normal development environment. First of all you should use SDL2. SDL is a library which takes care of platform-specific things like creating windows and handling input. An incomplete port of SDL 1.3 ships with Emscripten and there’s a port of full SDL2 in the works. It will be merged to upstream soon.

    Space combat in FTL.

    OpenGL ES 2.0

    Second thing is to use OpenGL ES 2.0. If your game is using the SDL2 render interface this has already been done for you. If you use Direct3D you’ll first have to create an OpenGL version of your game. This is why multiplatform support from the beginning is such a good idea.

    Once you have a desktop OpenGL version you then need to create an OpenGL ES version. ES is a subset of full OpenGL where some features are not available and there are some additional restrictions. At least the NVidia driver and probably also AMD support creating ES contexts on desktop. This has the advantage that you can use your existing environment and debugging tools.

    You should avoid the deprecated OpenGL fixed-function pipeline if possible. While Emscripten has some support for this it might not work very well.

    There are certain problems you can run into at this stage. First one is lack of extension support. Shaders might also need rewriting for Emscripten. If you are using NVidia add #version line to trigger stricter shader validation.

    GLSL ES requires precision qualifiers for floating-point and integer variables. NVidia accepts these on desktop but most other GL implementations not, so you might end up with two different sets of shaders.

    OpenGL entry point names are different between GL ES and desktop. GL ES does not require a loader such as GLEW but you still might have to check GL extensions manually if you are using any. Also note that OpenGL ES on desktop is more lenient than WebGL. For example WebGL is more strict about glTexImage parameters and glTexParameter sampling modes.

    Multiple render targets might not be supported on GL ES. If you are using a stencil buffer you must also have a depth buffer. You must use vertex buffer objects, not user-mode arrays. Also you cannot mix index and vertex buffers into the same buffer object.

    For audio you should use SDL2 or OpenAL. One potential issue is that the Emscripten OpenAL implementation might require more and larger sound buffers than desktop to avoid choppy sounds.

    Multiplatform support

    It’s good if your project has multiplatform support, especially for mobile platforms (Android, iOS). There are two reasons for this. First, WebGL is essentially OpenGL ES instead of desktop OpenGL so most of your OpenGL work is already done. Second, since mobile platforms use ARM architecture most of the processor-specific problems have already been fixed. Particularly important is memory alignment since Emscripten doesn’t support unaligned loads from memory.

    After you have your OpenGL sorted out (or even concurrently with it if you have multiple people) you should port your game to Linux and/or OS X. Again there are several reasons. First one is that Emscripten is based on LLVM and Clang. If your code was written and tested with MSVC it probably contains non standard constructs which MSVC will accept but other compilers won’t. Also different optimizer might expose bugs which will be much easier to debug on desktop than on a browser.

    FTL Emscripten version main menu. Notice the missing “Quit” button. The UI is similar to that of the iPad version.

    A good overview of porting a Windows game to Linux is provided in Ryan Gordon’s Steam Dev Days talk.

    If you are using Windows you could also compile with MinGW.

    Useful debugging tools


    The second reason for porting to Linux is to gain access to several useful tools. First among these is undefined behavior sanitizer (UBSan). It’s a Clang compiler feature which adds runtime checks to catch C/C++ undefined behavior in your code. Most useful of these is the unaligned load check. C/C++ standard specifies that when accessing a pointer it must be properly aligned. Unfortunately x86-based processors will perform unaligned loads so most existing code has not been checked for this. ARM-based processors will usually crash your program when this happens. This is why a mobile port is good. On Emscripten an unaligned load will not crash but instead silently give you incorrect results.

    UBSan is also available in GCC starting with 4.9 but unfortunately the unaligned load sanitizer is only included in the upcoming 5.0 release.


    Second useful tool in Clang (and GCC) is AddressSanitizer. This is a runtime checker which validates your memory accesses. Reading or writing outside allocated buffers can lead to crashes on any platform but the problem is somewhat worse on Emscripten. Native binaries have a large address space which contains lots of empty space. Invalid read, especially one that is only slightly off, might hit a valid address and so not crash immediately or at all. On Emscripten the address space is much “denser” so any invalid access is likely to hit something critical or even be outside the allocated address space entirely. This will trigger an unspectacular crash and might be very hard to debug.


    The third tool is Valgrind. It is a runtime tool which runs uninstrumented binaries and checks them for various properties. For our purposes the most useful are memcheck and massif. Memcheck is a memory validator like AddressSanitizer but it catches a slightly different set of problems. It can also be used to pinpoint memory leaks. Massif is a memory profiler which can answer the question “why am I using so much memory?” This is useful since Emscripten is also a much more memory-constrained platform than desktop or even mobile and has no built in tools for memory profiling.

    Valgrind also has some other checkers like DRD and Helgrind which check for multithreading issues but since Emscripten doesn’t support threads we won’t discuss them here. They are very useful though so if you do multithreading on desktop you really should be using them.

    Valgrind is not available on Windows and probably will never be. That alone should be a reason to port your games to other platforms.

    Third-party libraries

    Most games use a number of third-party libraries. Hopefully you’ve already gotten rid of any closed-source ones. But even open-source ones are usually shipped as already-compiled libraries. Most of these are not readily available on Emscripten so you will have to compile them yourself. Also the Emscripten object format is based on LLVM bytecode which is not guaranteed to be stable. Any precompiled libraries might no longer work in future versions of Emscripten.

    While Emscripten has some support for dynamic linking it is not complete or well supported and should be avoided.

    The best way around these issues is to build your libraries as part of your standard build process and statically link them. While bundling up your libraries to archives and including those in link step works you might run into unexpected problems. Also changing your compiler options becomes easier if all sources are part of your build system.

    Once all that is done you should actually try to compile with Emscripten. If you’re using MS Visual Studio 2010 there’s an integration module which you can try. If you’re using cmake Emscripten ships with a wrapper (emcmake) which should automatically configure your build.

    If you’re using some other build system it’s up to you to set it up. Generally CC=emcc and CXX=em++ should do the trick. You might also have to remove platform-specific options like SSE and such.

    Part 2: Emscripten itself

    So now it links but when you load it up in your browser it just hangs and after a while the browser will tell you the script has hung and kill it.

    What went wrong?

    On desktop games have an event loop which will poll input, simulate state and draw the scene and run until terminated. On a browser there is instead a callback which does these things and is called by the browser. So to get your game to work you have to refactor your loop to a callback. In Emscripten this is set with the function emscripten_set_main_loop. Fortunately in most cases this is pretty simple. The easiest way is to refactor the body of your loop to a helper function and then in your desktop version call it in a loop and in the browser set it as your callback. Or if you’re using C++11 you can use a lambda and store that in std::function. Then you can add a small wrapper which calls that.

    Problems appear if you have multiple separate loops, for example loading screens. In that case you need to either refactor them into a single loop or call them one after another, setting a new one and canceling the previous one with emscripten_cancel_main_loop. Both of these are pretty complex and depend heavily on your code.

    So, now the game runs but you get a bunch of error messages that your assets can’t be found. The next step is to add your assets to the package. The simple way is to preload them. Adding the switch --preload-file <filename> to link flags will cause Emscripten to add the specified files to a .data file which will then be preloaded before main is called. These files can then be accessed with standard C/C++ IO calls. Emscripten will take care of the necessary magic.

    However this approach becomes problematic when you have lots of assets. The whole package needs to be loaded before the program starts which can lead to excessive loading times. To fix this you can stream in some assets like music or video.

    If you already have async loading in your desktop code you can reuse that. Emscripten has the function emscripten_async_wget_data for loading data asynchronously. One difference to keep in mind is that Emscripten async calls only know asset size after loading has completed whereas desktop generally knows if after the file has been opened. For optimal results you should refactor your code to something like “load this file, then here’s an operation to do after you have it”. C++11 lambdas can be useful here. In any case you really should have matching code on the desktop version because debugging is so much easier there.

    You should add a call at the end of your main loop which handles async loads. You should not load too much stuff asynchronously as it can be slow, especially if you’re loading multiple small files.

    So now it runs for a while but crashes with a message about exceeded memory limit. Since Emscripten emulates memory with JavaScript arrays the size of those arrays is crucial. By default they are pretty small and can’t grow. You can enable growing them by linking with -s ALLOW_MEMORY_GROWTH=1 but this is slow and might disable asm.js optimizations. It’s mostly useful in the debugging phase. For final release you should find out a memory limit that works and use -s TOTAL_MEMORY=<number>.

    As described above, Emscripten doesn’t have a memory profiler. Use Valgrind massif tool on Linux to find out where the memory is spent.

    If your game is still crashing you can try using JavaScript debugger and source maps but they don’t necessarily work very well. This is why sanitizers are important. printf or other logging is a good way to debug too. Also -s SAFE_HEAP=1 in link stage can find some memory bugs.

    Osmos test version on Emscripten test html page.

    Saves and preferences

    Saving stuff is not as simple as on desktop. The first thing you should do is find all the places where you’re saving or loading user-generated data. All of it should be in one place or go through one wrapper. If it doesn’t you should refactor it on desktop before continuing.

    The simplest thing is to set up a local storage. Emscripten already has the necessary code to do it and emulate standard C-like filesystem interface so you don’t have to change anything.

    You should add something like this to either the preRun in html or first thing in your main:

    FS.createFolder('/', 'user_data', true, true)
    FS.mount(IDBFS, {}, '/user_data');
    FS.syncfs(true, function(err) {
                  if(err) console.log('ERROR!', err);
                  console.log('finished syncing..');

    Then after you’ve written a file you need to tell the browser to sync it. Add a new method which contains something like this:

    static void userdata_sync()
            FS.syncfs(function(error) {
                if (error) {
                    console.log("Error while syncing", error);

    and call it after closing the file.

    While this works it has the problem that the files are stored locally. For desktop games this is not a problem since users understand that saves are stored on their computer. For web-based games the users expect their saves to be there on all computers. For the Mozilla Bundle, Humble Bundle built a CLOUDFS library which works just like Emscripten’s IDBFS and has a pluggable backend. You need to build your own using emscripten GET and POST APIs.

    Osmos demo at the Humble Mozilla Bundle page.

    Making it fast

    So now your game runs but not very fast. How to make it faster?

    On Firefox the first thing to check is that asm.js is enabled. Open web console and look for message “Successfully compiled asm.js”. If it’s not there the error message should tell you what’s going wrong.

    The next thing to check is your optimization level. Emscripten requires proper -O option both when compiling and linking. It’s easy to forget -O from link stage since desktop doesn’t usually require it. Test the different optimization levels and read the Emscripten documentation about other build flags. In particular OUTLINING_LIMIT and PRECISE_F32 might affect code speed.

    You can also enable link-time optimization by adding --llvm-lto <n> option. But beware that this has known bugs which might cause incorrect code generation and will only be fixed when Emscripten is upgraded to a newer LLVM sometime in the future. You might also run into bugs in the normal optimizer since Emscripten is still somewhat work-in-progress. So test your code carefully and if you run into any bugs report them to Emscripten developers.

    One strange feature of Emscripten is that any preloaded resources will be parsed by the browser. We usually don’t want this since we’re not using the browser to display them. Disable this by adding the following code as --pre-js:

    var Module;
    if (!Module) Module = (typeof Module !== 'undefined' ? Module : null) || {};
    // Disable image and audio decoding
    Module.noImageDecoding = true;
    Module.noAudioDecoding = true;

    Next thing: don’t guess where the time is being spent, profile! Compile your code with --profiling option (both compile and link stage) so the compiler will emit named symbols. Then use the browser’s built-in JavaScript profiler to see which parts are slow. Beware that some versions of Firefox can’t profile asm.js code so you will either have to upgrade your browser or temporarily disable asm.js by manually removing use asm -statement from the generated JavaScript. You should also profile with both Firefox and Chrome since they have different performance characteristics and their profilers work slightly differently. In particular Firefox might not account for slow OpenGL functions.

    Things like glGetError and glCheckFramebuffer which are slow on desktop can be catastrophic in a browser. Also calling glBufferData or glBufferSubData too many times can be very slow. You should refactor your code to avoid them or do as much with one call as possible.

    Another thing to note is that scripting languages used by your game can be very slow. There’s really no easy way around this one. If your language provides profiling facilities you can use those to try to speed it up. The other option is to replace your scripts with native code which will get compiled to asm.js.

    If you’re doing physics simulation or something else that can take advantage of SSE optimizations you should be aware that currently asm.js doesn’t support it but it should be coming sometime soon.

    To save some space on the final build you should also go through your code and third party libraries and disable all features you don’t actually use. In particular libraries like SDL2 and freetype contain lots of stuff which most programs don’t use. Check the libraries’ documentation on how to disable unused features. Emscripten doesn’t currently have a way to find out which parts of code are the largest but if you have a Linux build (again, you should) you can use

    nm -S --size-sort game.bin

    to see this. Just be aware that what’s large on Emscripten and what’s large on native might not be the same thing. In general they should agree pretty well.

    Sweeping autumn leaves in Dustforce.

    In conclusion

    To sum up, porting an existing game to Emscripten consists of removing any closed-source third party libraries and threading, using SDL2 for window management and input, OpenGL ES for graphics, and OpenAL or SDL2 for audio. You should also first port your game to other platforms, such as OS X and mobile, but at least for Linux. This makes finding potential issues easier and gives access to several useful debugging tools. The Emscripten port itself minimally requires changes to main loop, asset file handling, and user data storage. Also you need to pay special attention to optimizing your code to run in a browser.

  2. Massive: The asm.js Benchmark

    asm.js is a subset of JavaScript that is very easy to optimize. Most often it is generated by a compiler, such as Emscripten, from C or C++ code. The result can run at very high speeds, close to that of the same code compiled natively. For that reason, Emscripten and asm.js are useful for things like 3D game engines, which are usually large and complex C++ codebases that need to be fast, and indeed top companies in the game industry have adopted this approach, for example Unity and Epic, and you can see it in action in the Humble Mozilla Bundle, which recently ran.

    As asm.js code becomes more common, it is important to be able to measure performance on it. There are of course plenty of existing benchmarks, including Octane which contains one asm.js test, and JetStream which contains several. However, even those do not contain very large code samples, and massive codebases are challenging in particular ways. For example, just loading a page with such a script can take significant time while the browser parses it, causing a pause that is annoying to the user.

    A recent benchmark from Unity measures the performance of their game engine, which (when ported to the web) is a large asm.js codebase. Given the high popularity of the Unity engine among developers, this is an excellent benchmark for game performance in browsers, as real-world as it can get, and also it tests large-scale asm.js. It does however focus on game performance as a whole, taking into account both WebGL and JavaScript execution speed. For games, that overall result is often what you care about, but it is also interesting to measure asm.js on its own.

    Benchmarking asm.js specifically

    Massive is a benchmark that measures asm.js performance specifically. It contains several large, real-world codebases: Poppler, SQLite, Lua and Box2D; see the FAQ on the massive site for more details on each of those.

    Massive reports an overall score, summarizing it’s individual measurements. This score can help browser vendors track their performance over time and point to areas where improvements are needed, and for developers it can provide a simple way to get an idea of how fast asm.js execution is on a particular device and browser.

    Importantly, Massive does not only test throughput. As already mentioned, large codebases can affect startup time, and they can also affect responsiveness and other important aspects of the user experience. Massive therefore tests, in addition to throughput, how long it takes the browser to load a large codebase, and how responsive it is while doing so. It also tests how consistent performance is. Once again, see the FAQ for more details on each of those.

    Massive has been developed openly on github from day one, and we’ve solicited and received feedback from many relevant parties. Over the last few months Massive development has been in beta while we received comments, and there are currently no substantial outstanding issues, so we are ready to announce the first stable version, Massive 1.0.

    Massive tests multiple aspects of performance, in new ways, so it is possible something is not being measured in an optimal manner, and of course bugs always exist in software. However, by developing Massive in the open and thereby giving everyone the chance to inspect it and report issues, and by having a lengthy beta period, we believe we have the best possible chance of a reliable result. Of course, if you do find something wrong, please file an issue! General feedback is of course always welcome as well.

    Massive performance over time

    Massive is brand-new, but it is still interesting to look at how it performs on older browsers (“retroactively”), because if it measures something useful, and if browsers are moving in the right direction, then we should see Massive improve over time, even on browser versions that were released long before Massive existed. The graph below shows Firefox performance from version 14 (released 2012-07-17, over 2 years ago) and version 32 (which became the stable version in September 2014):

    Higher numbers are better, so we can indeed see that Massive scores do follow the expected pattern of improvement, with Firefox’s Massive score rising to around 6x its starting point 2 years ago. Note that the Massive score is not “linear” in the sense that 6x the score means 6x the performance, as it is calculated using the geometric mean (like Octane), however, the individual scores it averages are mostly linear. A 6x improvement therefore does represent a very large and significant speedup.

    Looking more closely at the changes over time, we can see which features landed in each of those versions of Firefox where we can see a significant improvement:

    There are three big jumps in Firefox’s Massive score, each annotated:

    • Firefox 22 introduced OdinMonkey, an optimization module for asm.js code. By specifically optimizing asm.js content, it almost doubled Firefox’s Massive score. (At the time, of course, Massive didn’t exist; but we measured speedups on other benchmarks.)
    • Firefox 26 parses async scripts off of the main thread. This avoids the browser or page becoming nonresponsive while the script loads. For asm.js content, not only parsing but also compilation happens in the background, making the user experience even smoother. Also in Firefox 26 are general optimizations for float32 operations, which appear in one of the Massive tests.
    • Firefox 29 caches asm.js code: The second time you visit the same site, previously-compiled asm.js code will just be loaded from disk, avoiding any compilation pause at all. Another speedup in this version is that the previous float32 optimizations are fully optimized in asm.js code as well.

    Large codebases, and why we need a new benchmark

    Each of those features is expected to improve asm.js performance, so it makes sense to see large speedups there. So far, everything looks pretty much as we would expect. However, a fourth milestone is noted on that graph, and it doesn’t cause any speedup. That feature is IonMonkey, which landed in Firefox 18. IonMonkey was a new optimizing compiler for Firefox, and it provided very large speedups on most common browser benchmarks. Why, then, doesn’t it show any benefit in Massive?

    IonMonkey does help very significantly on small asm.js codebases. But in its original release in Firefox 18 (see more details in the P.S. below), IonMonkey did not do well on very large ones – as a complex optimizing compiler, compilation time is not necessarily linear, which means that large scripts can take very large amounts of time to compile. IonMonkey therefore included a script size limit – over a certain size, IonMonkey simply never kicks in. This explains why Massive does not improve on Firefox 18, when IonMonkey landed – Massive contains very large codebases, and IonMonkey at the time could not actually run on them.

    That shows exactly why a benchmark like Massive is necessary, as other benchmarks did show speedups upon IonMonkey’s launch. In other words, Massive is measuring something that other benchmarks do not. And that thing – large asm.js codebases – is becoming more and more important.

    (P.S. IonMonkey’s script size limit prevented large codebases from being optimized when IonMonkey originally launched, but that limit has been relaxed over time, and practically does not exist today. This is possible through compilation on a background thread, interruptible compilation, and just straightforward improvements to compilation speed, all of which make it feasible to compile larger and larger functions. Exciting general improvements to JavaScript engines are constantly happening across the board!)

  3. Introducing SIMD.js

    SIMD stands for Single Instruction Multiple Data, and is the name for performing operations on multiple data elements together. For example, a SIMD add instruction can add multiple values, in parallel. SIMD is a very popular technique for accelerating computations in graphics, audio, codecs, physics simulation, cryptography, and many other domains.

    In addition to delivering performance, SIMD also reduces power usage, as it uses fewer instructions to do the same amount of work.


    SIMD.js is a new API being developed by Intel, Google, and Mozilla for JavaScript which introduces several new types and functions for doing SIMD computations. For example, the Float32x4 type represents 4 float32 values packed up together. The API contains functions to operate on those values together, including all the basic arithmetic operations, and operations to rearrange, load, and store such values. The intent is for browsers to implement this API directly, and provide optimized implementations that make use of SIMD instructions in the underlying hardware.

    The focus is currently on supporting both x86 platforms with SSE and ARM platforms with NEON. We’re also interested in the possibility of supporting other platforms, potentially including MIPS, Power, and others.

    SIMD.js is originally derived from the Dart SIMD specification, and it is rapidly evolving to become a more general API, and to cover additional use cases such as those that require narrower integer types, including Int8x16 and Int16x8, and saturating operations.

    SIMD.js is a fairly low-level API, and it is expected that libraries will be written on top of it to expose higher-level functionality such as matrix operations, transcendental functions, and more.

    In addition to being usable in regular JS, there is also work is underway to add SIMD.js to asm.js too, so that it can be used from asm.js programs such those produced by Emscripten. In Emscripten, SIMD can be achieved through the built-in autovectorization, the generic SIMD extensions, or the new (and still growing) Emscripten-specific API. Emscripten will also be implementing subsets of popular headers such as <xmmintrin.h> with wrappers around the SIMD.js APIs, as additional ways to ease porting SIMD code in some situations.

    SIMD.js Today

    The SIMD.js API itself is in active development. The ecmascript_simd github repository is currently serving as a provision specification as well as providing a polyfill implementation to provide the functionality, though of course not the accelerated performance, of the SIMD API on existing browsers. It also includes some benchmarks which also serve as examples of basic SIMD.js usage.

    To see SIMD.js in action, check out the demo page accompanying the IDF2014 talk on SIMD.js.

    The API has been presented to TC-39, which has approved it for stage 1 (Proposal). Work is proceeding in preparation for subsequent stages, which will involve proposing something closer to a finalized API.

    SIMD.js implementation in Firefox Nightly is in active development. Internet Explorer has listed SIMD.js as “under consideration”. There is also a prototype implementation in a branch of Chromium.

    Short SIMD and Long SIMD

    One of the uses of SIMD is to accelerate processing of large arrays of data. If you have an array of N elements, and you want to do roughly the same thing to every element in the array, you can divide N by whatever SIMD size the platform makes available and run that many instances of your SIMD subroutine. Since N can can be very large, I call these kind of problems long SIMD problems.

    Another use of SIMD is to accelerate processing of clusters of data. RGB or RGBA pixels, XYZW coordinates, or 4×4 matrices are all examples of such clusters, and I call problems which are expressed in these kinds of types short SIMD problems.

    SIMD is a broad domain, and the boundary between short and long SIMD isn’t always clear, but at a high level, the two styles are quite different. Even the terminology used to describe them features a split: In the short SIMD world, the operation which copies a scalar value into every element of a vector value is called a “splat”, while in the long vector world the analogous operation is called a “broadcast”.

    SIMD.js is primarily a “short” style API, and is well suited for short SIMD problems. SIMD.js can also be used for long SIMD problems, and it will still deliver significant speedups over plain scalar code. However, its fixed-length types aren’t going to achieve maximum performance of some of today’s CPUs, so there is still room for another solution to be developed to take advantage of that available performance.

    Portability and Performance

    There is a natural tension in many parts of SIMD.js between the desire to have an API which runs consistently across all important platforms, and the desire to have the API run as fast as possible on each individual platform.

    Fortunately, there is a core set of operations which are very consistent across a wide variety of platforms. These operations include most of the basic arithmetic operations and form the core of SIMD.js. In this set, little to no overhead is incurred because many of the corresponding SIMD API instructions map directly to individual instructions.

    But, there also are many operations that perform well on one platform, and poorly on others. These can lead to surprising performance cliffs. The current approach of the SIMD.js API is to focus on the things that can be done well with as few performance cliffs as possible. It is also focused on providing portable behavior. In combination, the aim is to ensure that a program which runs well on one platform will likely run and run well on another.

    In future iterations of SIMD.js, we expect to expand the scope and include more capabilities as well as mechanisms for querying capabilities of the underlying platform. Similar to WebGL, this will allow programs to determine what capabilities are available to them so they can decide whether to fall back to more conservative code, or disable optional functionality.

    The overall vision

    SIMD.js will accelerate a wide range of demanding applications today, including games, video and audio manipulation, scientific simulations, and more, on the web. Applications will be able to use the SIMD.js API directly, libraries will be able to use SIMD.js to expose higher-level interfaces that applications can use, and Emscripten will compile C++ with popular SIMD idioms onto optimized SIMD.js code.

    Looking forward, SIMD.js will continue to grow, to provide broader functionality. We hope to eventually accompany SIMD.js with a long-SIMD-style API as well, in which the two APIs can cooperate in a manner very similar to the way that OpenCL combines explicit vector types with the implicit long-vector parallelism of the underlying programming model.

  4. Generational Garbage Collection in Firefox

    Generational garbage collection (GGC) has now been enabled in the SpiderMonkey JavaScript engine in Firefox 32. GGC is a performance optimization only, and should have no observable effects on script behavior.

    So what is it? What does it do?

    GGC is a way for the JavaScript engine to collect short-lived objects faster. Say you have code similar to:

    function add(point1, point2) {
        return [ point1[0] + point2[0], point1[1] + point2[1] ];

    Without GGC, you will have high overhead for garbage collection (from here on, just “GC”). Each call to add() creates a new Array, and it is likely that the old arrays that you passed in are now garbage. Before too long, enough garbage will pile up that the GC will need to kick in. That means the entire JavaScript heap (the set of all objects ever created) needs to be scanned to find the stuff that is still needed (“live”) so that everything else can be thrown away and the space reused for new objects.

    If your script does not keep very many total objects live, this is totally fine. Sure, you’ll be creating tons of garbage and collecting it constantly, but the scan of the live objects will be fast (since not much is live). However, if your script does create a large number of objects and keep them alive, then the full GC scans will be slow, and the performance of your script will be largely determined by the rate at which it produces temporary objects — even when the older objects aren’t changing, and you’re just re-scanning them over and over again to discover what you already knew. (“Are you dead?” “No.” “Are you dead?” “No.” “Are you dead?”…)

    Generational collector, Nursery & Tenured

    With a generational collector, the penalty for temporary objects is much lower. Most objects will be allocated into a separate memory region called the Nursery. When the Nursery fills up, only the Nursery will be scanned for live objects. The majority of the short-lived temporary objects will be dead, so this scan will be fast. The survivors will be promoted to the Tenured region.

    The Tenured heap will also accumulate garbage, but usually at a far lower rate than the Nursery. It will take much longer to fill up. Eventually, we will still need to do a full GC, but under typical allocation patterns these should be much less common than Nursery GCs. To distinguish the two cases, we refer to Nursery collections as minor GCs and full heap scans as major GCs. Thus, with a generational collector, we split our GCs into two types: mostly fast minor GCs, and fewer slower major GCs.

    GGC Overhead

    While it might seem like we should have always been doing this, it turns out to require quite a bit of infrastructure that we previously did not have, and it also incurs some overhead during normal operation. Consider the question of how to figure out whether some Nursery object is live. It might be pointed to by a live Tenured object — for example, if you create an object and store it into a property of a live Tenured object.

    How do you know which Nursery objects are being kept alive by Tenured objects? One alternative would be to scan the entire Tenured heap to find pointers into the Nursery, but this would defeat the whole point of GGC. So we need a way of answering the question more cheaply.

    Note that these Tenured ⇒ Nursery edges in the heap graph won’t last very long, because the next minor GC will promote all survivors in the Nursery to the Tenured heap. So we only care about the Tenured objects that have been modified since the last minor (or major) GC. That won’t be a huge number of objects, so we make the code that writes into Tenured objects check whether it is writing any Nursery pointers, and if so, record the cross-generational edges in a store buffer.

    In technical terms, this is known as a write barrier. Then, at minor GC time, we walk through the store buffer and mark every target Nursery object as being live. (We actually use the source of the edge at the same time, since we relocate the Nursery object into the Tenured area while marking it live, and thus the Tenured pointer into the Nursery needs to be updated.)

    With a store buffer, the time for a minor GC is dependent on the number of newly-created edges from the Tenured area to the Nursery, not just the number of live objects in the Nursery. Also, keeping track of the store buffer records (or even just the checks to see whether a store buffer record needs to be created) does slow down normal heap access a little, so some code patterns may actually run slower with GGC.

    Allocation Performance

    On the flip side, GGC can speed up object allocation. The pre-GGC heap needs to be fully general. It must track in-use and free areas and avoid fragmentation. The GC needs to be able to iterate over everything in the heap to find live objects. Allocating an object in a general heap like this is surprisingly complex. (GGC’s Tenured heap has pretty much the same set of constraints, and in fact reuses the pre-GGC heap implementation.)

    The Nursery, on the other hand, just grows until it is full. You never need to delete anything, at least until you free up the whole Nursery during a minor GC, so there is no need to track free regions. Consequently, the Nursery is perfect for bump allocation: to allocate N bytes you just check whether there is space available, then increment the current end-of-heap pointer by N bytes and return the previous pointer.

    There are even tricks to optimize away the “space available” check in many cases. As a result, objects with a short lifespan never go through the slower Tenured heap allocation code at all.


    I wrote a simple benchmark to demonstrate the various possible gains of GGC. The benchmark is sort of a “vector Fibonacci” calculation, where it computes a Fibonacci sequence for both the x and y components of a two dimensional vector. The script allocates a temporary object on every iteration. It first times the loop with the (Tenured) heap nearly empty, then it constructs a large object graph, intended to be placed into the Tenured portion of the heap, and times the loop again.

    On my laptop, the benchmark shows huge wins from GGC. The average time for an iteration through the loop drops from 15 nanoseconds (ns) to 6ns with an empty heap, demonstrating the faster Nursery allocation. It also shows the independence from the Tenured heap size: without GGC, populating the long-lived heap slows down the mean time from 15ns to 27ns. With GGC, the speed stays flat at 6ns per iteration; the Tenured heap simply doesn’t matter.

    Note that this benchmark is intended to highlight the improvements possible with GGC. The actual benefit depends heavily on the details of a given script. In some scripts, the time to initialize an object is significant and may exceed the time required to allocate the memory. A higher percentage of Nursery objects may get tenured. When running inside the browser, we force enough major GCs (eg, after a redraw) that the benefits of GGC are less noticeable.

    Also, the description above implies that we will pause long enough to collect the entire heap, which is not the case — our incremental garbage collector dramatically reduces pause times on many Web workloads already. (The incremental and generational collectors complement each other — each attacks a different part of the problem.)


  5. WebIDE, Storage inspector, jQuery events, iframe switcher + more – Firefox Developer Tools Episode 34

    A new set of Firefox Developer Tools features has just been uplifted to the Aurora channel. These features are available right now in Aurora, and will be in the Firefox 34 release in November. This release brings new tools (storage inspector, WebIDE), an updated profiler, and handy enhancements to the existing tools:


    WebIDE, a new tool for in-browser app development, has been enabled by default in this release. WebIDE lets you create a new Firefox OS app (which is just a web app) from a template, or open up the code for an already created app. From there you can edit the app’s files. It’s one click to run the app in a simulator and one more to debug it with the developer tools. Open WebIDE from Firefox’s “Web Developer” menu. (docs)

    Storage inspector

    There’s a new panel that shows the data your page has stored in cookies, localStorage, sessionStorage, and IndexedDB, which was created mostly by Girish Shama. Enable the Storage panel by checking off Settings > “Default Developer Tools” > “Storage”. The panel is read-only right now, with editing ability planned for a future release. (docs) (development notes) (UserVoice request)

    storage inspector

    jQuery events

    The event listener popup in the Inspector now supports jQuery. This means the popup will display the function you attached with e.g. jQuery.on(), and not the jQuery wrapper function itself. See this post for more info and how to add support for your preferred framework. (development notes)

    JQuery events

    Iframe switcher

    Change the frame you’re debugging using the new frame selection menu. Selecting a frame will switch all of the tools to debug that iframe, including the Inspector, Console, and Debugger. Add the frame selection button by checking off Settings > “Available Toolbox Buttons” > “Select an iframe”. (docs) (development notes)(UserVoice request)

    iframe selection

    Updated profiler

    An updated JavaScript profiler appears in the new “Performance” tab (formerly the “Profiler” tab). New to the profiler are a frame rate timeline and categories for frames like “network” and “graphics”. (docs) (development notes)

    new profiler


    Add a call to console.table() anywhere in your JavaScript to log data to the console using a table-like display. Log any object, array, Map, or Set. Sort a column in the table by clicking on its header. (docs) (development notes)


    Selector preview

    Hover over a CSS selector in the Inspector or Style Editor to highlight all the nodes that match that selector on the page. (development notes)

    selector previews

    Other mentions

    • Persistent split console – The split console (opened by pressing ESC) will now open with the tools if you had it open the last time the tools were closed. (development notes)
    • Web audio – AudioParam connections – the Web Audio Editor now displays connections from AudioNodes to AudioParams. (development notes)

    Special thanks to the 41 contributors that added all the features and fixes in this release.

    Comment here, shoot feedback to @FirefoxDevTools on Twitter, or propose changes on the Developer Tools feedback channel. If you’d like to help out, check out the guide to getting involved.

  6. Introducing Blast.js

    After releasing Velocity.js, a highly performant web animation engine, I wanted to leverage that power for typographic manipulation. The question soon arose, How could I animate one letter, one word, or one sentence at a time without bloating my HTML with wrapper elements?

    If I could figure this out, I could create beautiful typographic animation sequences (the kind you see in movie titles), and perform real-time textual analysis.

    After researching lower-level DOM methods and polishing my RegEx skills, I built Blast.js: a jQuery/Zepto plugin that breaks apart text to enable hassle-free text manipulation. Follow that link to see a few demos.

    Let’s jump right into a code example. If we were to Blast an element using the following syntax…

    $("div").blast({ delimiter: "word" });

    …and if our element initially looked like this…

        Hello World

    …our element would now look like this:

    <div class="blast-root">
        <span class="blast">Hello</span>
        <span class="blast">World</span>

    The div’s text was broken into individual span elements using the specified word delimiter. We could have used the character, sentence, or element delimiters instead.

    For a breakdown of Blast’s API, refer to its documentation.

    This article serves to explore the technical aspects that went into making Blast versatile and accurate: We’ll learn about very powerful, yet little-known, DOM traversal techniques plus how to maximally leverage RegEx for linguistic accuracy.

    If you’re interested in the technical aspects of how rich motion design works or how to manipulate text, this article is for you.


    Most DOM elements are composed of descendant text nodes. Blast traverses the entirety of the HTML element that it is targeted on, descending recursively until it’s found every descendant text node.

    For example, if you Blast the following HTML:

    <div>Hello <span>World</span></div>

    The containing div is an element node. This element node is composed of two children: 1) a text node (“Hello “) and 2) a span element node. The span element node contains one child: a text node of its own (“World”).

    With each text node Blast finds, it executes the RegEx query associated with the chosen delimiter type (e.g. character, word, or sentence) in order to find submatches. For example, a text node of “World” blasted with the character delimiter will produce five submatches: “w”, “o”, “r”, “l”, and “d”. Blast wraps a new element node of a user-defined type (span is the default) around each of these submatches.

    By traversing the DOM in this way, Blast can be applied safely to the entirety of an element without concern for breaking any of its descendant HTML or its associated event handlers. (Event handlers are never bound to text nodes, but rather to containing element nodes.)

    In fact, let’s try just that — in real-time! Click here to see Blast used on a CodePen page with the word delimiter. Notice how the generated wrapper elements are filtered with alternating colors. Next, click around. You’ll see that the page continues to work perfectly; all buttons, event handlers, and interactions remain fully intact. Nothing has been compromised.

    This versatility is crucial when blasting user-generated content, which, by its nature, is not necessarily predictably structured. It can be dirtied with HTML.


    When Blast generates wrappers around each of text node’s submatches, it assigns each wrapper a “blast” class. This class is later referenced when Blast is reversed.

    Blast reversal is triggered by passing in false as Blast’s sole parameter. The reversal process works as follows: The DOM is traversed, but the elements it’s looking for are element nodes (not text nodes) that have been assigned the “blast” class. Each matched element node is then replaced with its inner HTML.

    For example, reversing Blast on the following HTML…

    <div id="helloWorld" class="blast-root">
        <span class="blast">Hello</span>
        <span class="blast">World</span>

    … using the following syntax…


    …will result in Blast descending into #helloWorld, matching each element node individually, then substituting these element nodes with the text nodes that they contain — “Hello” and “World”, respectively.

    After this process, our DOM is back to exactly where it was before we Blasted it. This ability to cleanly reverse allows us to jump into arbitrarily structured HTML, Blast it apart, run a series of typographic animations, then reverse Blast upon completion so that our markup remains clean and structured as originally intended.

    Let’s do just that:

    See the Pen Blast.js – Command: Reverse by Julian Shapiro (@julianshapiro) on CodePen.


    We’ve established that Blast preserves HTML by touching only the relevant nodes (text nodes). Now let’s explore how Blast is able to pull off this next trick:

    See the Pen Blast.js TypeKit Article – Accuracy by Julian Shapiro (@julianshapiro) on CodePen.

    Remember, when a descendant text node is found in an element node targeted by Blast, the chosen delimiter’s RegEx is executed against it. Let’s examine each delimiter, starting with the simplest: character.

    (Note that you can follow along with these examples by clicking the demo buttons under the Robustness Gallery section of Blast’s documentation. You can also visit to test the following RegEx queries against your own bodies of text.)

    The RegEx for the character delimiter is simply /(S)/, which treats every non-space character as a submatch (a submatch is the part of the text node that gets wrapped by a newly-generated element). Simple enough.

    Next, the word delimiter uses this RegEx: /s*(S+)s*/. This matches any non-space character surrounded by either a space or nothing (nothing is the edge case where a word appears at the beginning or ending of a text node). Specifically, s* means “optionally match a space character”, and the S+ in the middle means “match as many non-space characters as possible.” Note that the word delimiter matches will include any punctuation that’s adjoined to the word, e.g. “Hey!” will be a full match. For the vast majority of use cases, this is more desirable than treating every adjoined punctuation as its own word.

    Now things start to get more complex. It’s trivial to match characters and space-delimited words, but it’s tricky to robustly match sentences — especially in a multilingual manner. Blast’s sentence delimiter delimits phrases either 1) ending in Latin alphabet punctuation (linebreaks are not considered punctuation) or 2) located at the end of a body of text. The sentence delimiter’s RegEx looks like this:


    Below is an expanded view (with spacing) for better legibility:

    (?=S) ( ([.]{2,})? [^!?]+? ([.…!?]+|(?=s+$)|$) (s*[′’'”″“")»]+)* )

    Let’s break that down into its components:

    • (?=S) The sentence must contain a non-space character.
    • ([.]{2,})? The sentence may begin with a group of periods, e.g. “… that was a bad idea, Tom!”
    • [^!?]+? Grab everything that isn’t an unequivocally-terminating punctuation character, but stop when the following condition is reached…
    • ([.…!?]+|(?=s+$)|$) …match the last occurrence of sentence-final punctuation or the end of the text (optionally with trailing spaces).
    • (s*[′’'”″“")»]+)* After the final punctuation is matched, also include any and all pairs of (optionally space-delimited) quotes and parentheses.

    That’s quite a bit to to digest, but if you refer to those RegEx components while revisiting the sentence matching behavior from the top of this section (re-embedded below for convenience), you’ll start to see how the larger pieces come together.

    See the Pen Blast.js TypeKit Article – Accuracy by Julian Shapiro (@julianshapiro) on CodePen.

    (Click on the HTML tab to modify the HTML and see how Blast behaves on different bodies of text.)

    We still haven’t explained why that embedded demo’s errant periods aren’t falsely triggering the end of a sentence match: The trick is to perform a pre-pass on each text node — prior to the primary RegEx execution — in which likely false positives are rendered inert by temporary encoding them into non-matching strings. Then, after the sentence RegEx is executed, the likely false positives are decoded back to their original characters.

    The false positive encoding process consists of replacing a punctuation character with its ASCII equivalent inside double curly brackets. For example, a likely false positive period (e.g. one found in the title “Mr. Johnson”) will be turned into “Mr{{46}} Johnson”. Then, when the sentence delimiter’s RegEx is executed, it skips over the {{46}} block since curly braces aren’t considered Latin alphabet punctuation.

    Here’s the logic behind this process:

    /* Escape the following Latin abbreviations and English
       titles: e.g., i.e., Mr., Mrs., Ms., Dr., Sr., and Jr. */
    .replace(RegEx.abbreviations, function(match) {
        return match.replace(/./g, "{{46}}");
    /* Escape inner-word (non-space-delimited) periods.
       For example, the period inside "Blast.js". */
    .replace(RegEx.innerWordPeriod, function(match) {
       return match.replace(/./g, "{{46}}");

    So now you have an overview of Blast’s behavior, but you haven’t learned that much. Not to worry, the next two sections get super technical.

    Deep dive: Regex

    This section is optional. This is a technical deep dive into how Blast’s RegEx queries are designed.

    This is the RegEx code block that you can find at the top of Blast’s source code:

    var characterRanges = {
            latinLetters: "\u0041-\u005A\u0061-\u007A\u00C0-\u017F\u0100-\u01FF\u0180-\u027F",
        Reg = {
            abbreviations: new RegExp("[^" + characterRanges.latinLetters + "](e\.g\.)|(i\.e\.)|(mr\.)|(mrs\.)|(ms\.)|(dr\.)|(prof\.)|(esq\.)|(sr\.)|(jr\.)[^" + characterRanges.latinLetters + "]", "ig"),
            innerWordPeriod: new RegExp("[" + characterRanges.latinLetters + "].[" + characterRanges.latinLetters + "]", "ig"),

    The first step is to define the UTF8 character ranges within which the letters used by all the Latin alphabet languages are contained. If that string looks like total gibberish to you, fear not: Character representation systems associate an ID with each of their displayable characters. RegEx simply allows us to define a range of ID’s (place a “-” between your first character’s ID and the last character’s ID). We take advantange of this by collating a bunch of ID ranges together in order to skip past ranges that contain characters that aren’t used in everyday language (e.g. emoticons, arrow symbols, etc.).

    Once we know what all the acceptable characters are, we can use them to create RegEx queries:

    The abbreviations RegEx looks for case-insensitive whitelisted abbreviations (e.g. Mr., Dr. Jr.) that are not immediately preceded by one of the accepted characters. In other words, it wants to find where these abbreviations are preceded by either nothing, a space, or a non-letter character. For example, we don’t want to match “ms.” in “grams.”, but we want to match “ms.” in “→Ms. Piggy”. Likewise, the RegEx query ensures that the abbreviation is also not immediately followed by a letter. For example, we don’t want to match “e.g.” in a corporation’s name abbreviation such as “E.G.G.S.”. But, we do want to match “e.g.” in “… farm animals, e.g. cows, bigs, etc.”

    The inner-word period RegEx looks for any period that’s sandwiched immediately between a whitelisted Latin alphabet letters on either side. So, the period inside “Blast.js” successfully matches, but the period at the end of “This is is a short sentence.” successfully does not.

    Deep dive: DOM traversal

    This section is optional. This is a deep dive into how text node traversal works.

    Let’s take a look at the recursive DOM traversal code:

    if (node.nodeType === 1 && node.hasChildNodes()
        && !Reg.skippedElements.test(node.tagName)
        && !Reg.hasPluginClass.test(node.className)) {
        /* Note: We don't cache childNodes' length since it's a live nodeList (which changes dynamically with the use of splitText() above). */
        for (var i = 0; i < node.childNodes.length; i++) {
            Element.nodeBeginning = true;
            i += traverseDOM(node.childNodes[i], opts);

    Above, we check that the node…

    • Has a nodeType of 1 (which is the ID associated with an element node).
    • Has child nodes for us to crawl.
    • Is not one of the blacklisted element node tags (script, textarea, and select), which contain text nodes, but not that typical kind that users likely want to be blasted.
    • Isn’t already assigned the “blast” class, which Blast uses to keep track of which elements it’s currently being used on.

    If the above conditions aren’t true and if the nodeType is instead returning a value of 3, then we know we’ve hit an actual text node. In this case, we proceed with submatch and element wrapping logic. Refer to the inlined comments for a thorough walkthrough:

    /* Find what position in the text node that our
    delimiter's RegEx returns a match. */
    matchPosition =;
    /* If there's a RegEx match in this text node, proceed
       with element wrapping. */
    if (matchPosition !== -1) {
        /* Return the match. */
        var match =,
            /* Get the node's full text. */
            matchText = match[0],
            /* Get only the match's text. */
            subMatchText = match[1] || false;
        /* RegEx queries that can return empty strings (e.g ".*")
           produce an empty matchText which throws the entire
           traversal process into an infinite loop due to the
           position index not incrementing. Thus, we bump up
           the position index manually, resulting in a zero-width
           split at this location followed by the continuation
           of the traversal process. */
        if (matchText === "") {
        /* If a RegEx submatch is produced that is not
           identical to the full string match, use the submatch's
           index position and text. This technique allows us to
           avoid writing multi-part RegEx queries for submatch finding. */
        } else if (subMatchText &amp;&amp; subMatchText !== matchText) {
            matchPosition += matchText.indexOf(subMatchText);
            matchText = subMatchText;
        /* Split this text node into two separate nodes at the
           position of the match, returning the node that begins
           after the match position. */
        var middleBit = node.splitText(matchPosition);
        /* Split the newly-produced text node at the end of the
           match's text so that middleBit is a text node that
           consists solely of the matched text. The other
           newly-created text node, which begins at the end
           of the match's text, is what will be traversed in
           the subsequent loop (in order to find additional
           matches in the containing text node). */
        /* Over-increment the loop counter so that we skip
           the extra node (middleBit) that we've just created
           (and already processed). */
        skipNodeBit = 1;
        /* Create the wrapped node. Note: wrapNode code
           is not shown, but it simply consists of creating
           a new element and assigning it an innerText value. */
        var wrappedNode = wrapNode(middleBit);
        /* Then replace the middleBit text node with its
           wrapped version. */
        middleBit.parentNode.replaceChild(wrappedNode, middleBit);

    This process isn’t tremendously performant when used on a large bodies of text with a delimiter that produces a lot of small matches (namely, the character delimiter), but it’s phenomenally robust and reliable.

    Wrapping up

    Go forth and blast shit up ;-) If you create something cool, please post it on CodePen and share it in the comments below.

    Follow me on Twitter for tweets about UI manipulation.

  7. Black Box Driven Development in JavaScript

    Sooner or later every developer finds the beauty of the design patterns. Also, sooner or later the developer finds that most of the patterns are not applicable in their pure format. Very often we use variations. We change the well-known definitions to fit in our use cases. I know that we (the programmers) like buzzwords. Here is a new one – Black Box Driven Development or simply BBDD. I started applying the concept before a couple of months, and I could say that the results are promising. After finishing several projects, I started seeing the good practices and formed three principles.

    What is a black box?

    Before to go with the principles of the BBDD let’s see what is meant by a black box. According to Wikipedia:

    In science and engineering, a black box is a device, system or object which can be viewed in terms of its input, output and transfer characteristics without any knowledge of its internal workings.

    In programming, every piece of code that accepts input, performs actions and returns an output could be considered as a black box. In JavaScript, we could apply the concept easily by using a function. For example:

    var Box = function(a, b) {
        var result = a + b;
        return result;

    This is the simplest version of a BBDD unit. It is a box that performs an operation and returns output immediately. However, very often we need something else. We need continuous interaction with the box. This is another kind of box that I use to call living black box.

    var Box = function(a, b) {
        var api = {
            calculate: function() {
                return a + b;
        return api;

    We have an API containing all the public functions of the box. It is identical to the revealing module pattern. The most important characteristic of this pattern is that it brings encapsulation. We have a clear separation of the public and private objects.

    Now that we know what a black box is, let’s check out the three principles of BBDD.

    Principle 1: Modulize everything

    Every piece of logic should exist as an independent module. In other words – a black box. In the beginning of the development cycle it is a little bit difficult to recognize these pieces. Spending too much time in architecting the application without having even a line of code may not produce good results. The approach that works involves coding. We should sketch the application and even make part of it. Once we have something we could start thinking about black boxing it. It is also much easier to jump into the code and make something without thinking if it is wrong or right. The key is to refactor the implementation till you feel that it is good enough.

    Let’s take the following example:

    $(document).ready(function() {
        if(window.localStorage) {
            var products = window.localStorage.getItem('products') || [], content = '';
            for(var i=0; i<products.length; i++) {
                content += products[i].name + '<br />';
        } else {
            $('.error').css('display', 'block');
            $('.error').html('Error! Local storage is not supported.')

    We are getting an array called products from the local storage of the browser. If the browser does not support local storage, then we show a simple error message.

    The code as it is, is fine, and it works. However, there are several responsibilities that are merged into a single function. The first optimization that we have to do is to form a good entry point of our code. Sending just a newly defined closure to the $(document).ready is not flexible. What if we want to delay the execution of our initial code or run it in a different way. The snippet above could be transformed to the following:

    var App = function() {
        var api = {};
        api.init = function() {
            if(window.localStorage) {
                var products = window.localStorage.getItem('products') || [], content = '';
                for(var i=0; i<products.length; i++) {
                    content += products[i].name + '<br />';
            } else {
                $('.error').css('display', 'block');
                $('.error').html('Error! Local storage is not supported.');
            return api;
        return api;
    var application = App();

    Now, we have better control over the bootstrapping.

    The source of our data at the moment is the local storage of the browser. However, we may need to fetch the products from a database or simply use a mock-up. It makes sense to extract this part of the code:

    var Storage = function() {
        var api = {};
        api.exists = function() {
            return !!window && !!window.localStorage;
        api.get = function() {
            return window.localStorage.getItem('products') || [];
        return api;

    We have two other operations that could form another box – setting HTML content and show an element. Let’s create a module that will handle the DOM interaction.

    var DOM = function(selector) {
        var api = {}, el;
        var element = function() {
            if(!el) {
                el = $(selector);
                if(el.length == 0) {
                    throw new Error('There is no element matching "' + selector + '".');
            return el;
        api.content = function(html) {
            return api;
        } = function() {
            element().css('display', 'block');
            return api;
        return api;

    The code is doing the same thing as in the first version. However, we have a test function element that checks if the passed selector matches anything in the DOM tree. We are also black boxing the jQuery element that makes our code much more flexible. Imagine that we decide to remove jQuery. The DOM operations are hidden in this module. It is worth nothing to edit it and start using vanilla JavaScript for example or some other library. If we stay with the old variant, we will probably go through the whole code base replacing code snippets.

    Here is the transformed script. A new version that uses the modules that we’ve created above:

    var App = function() {
        var api = {},
            storage = Storage(),
            c = DOM('.content'),
            e = DOM('.error');
        api.init = function() {
            if(storage.exists()) {
                var products = storage.get(), content = '';
                for(var i=0; i<products.length; i++) {
                    content += products[i].name + '<br />';
            } else {
                e.content('Error! Local storage is not supported.').show();
            return api;
        return api;

    Notice that we have separation of responsibilities. We have objects that play roles. It is easier and much more interesting to work with such codebase.

    Principle 2: Expose only public methods

    What makes the black box valuable is the fact that it hides the complexity. The programmer should expose only methods (or properties) that are needed. All the other functions that are used for internal processes should be private.

    Let’s get the DOM module above:

    var DOM = function(selector) {
        var api = {}, el;
        var element = function() {}
        api.content = function(html) {} = function() {}
        return api;

    When a developer uses our class, he is interested in two things – changing the content and showing a DOM element. He should not think about validations or change CSS properties. In our example, there are private variable el and private function element. They are hidden from the outside world.

    Principle 3: Use composition over inheritance

    One of the popular ways to inherit classes in JavaScript uses the prototype chain. In the following snippet, we have class A that is inherited by class C:

    function A(){};
    A.prototype.someMethod = function(){};
    function C(){};
    C.prototype = new A();
    C.prototype.constructor = C;

    However, if we use the revealing module pattern, it makes sense to use composition. It is because we are dealing with objects and not functions (* in fact the functions in JavaScript are also objects). Let’s say that we have a box that implements the observer pattern, and we want to extend it.

    var Observer = function() {
        var api = {}, listeners = {};
        api.on = function(event, handler) {}; = function(event, handler) {};
        api.dispatch = function(event) {};
        return api;
    var Logic = function() {
        var api = Observer();
        api.customMethod = function() {};
        return api;

    We get the required functionality by assigning an initial value to the api variable. We should notice that every class that uses this technique receives a brand new observer object so there is no way to produce collisions.


    Black box driven development is a nice way to architect your applications. It provides encapsulation and flexibility. BBDD comes with a simple module definition that helps organizing big projects (and teams). I saw how several developers worked on the same project, and they all built their black boxes independently.

  8. Browserify and Gulp with React

    The JS world moves quickly, and nowadays, there’re some new kids around the block. Today, we’ll explore Browserify, Gulp, and React and see whether they’d sound suitable for our projects. You might have heard of them but not have had the time to check them out. So we’ll look at the advantages and disadvantages of using Browserify, using Gulp, using React. Because it certainly doesn’t hurt to know our options.

    Browserify: Bundling Node Modules for the Browser

    Browserify is a development tool lets us write Node-style modules in the browser or include actual Node modules from npm. Modules are written in separate files, things can be exported, and modules pull in other modules through require. Browserify can then parse our main JS module, building a dependency tree, to bundle everything together.

    One great thing is that the tens of thousands of modules on NPM are now available for our projects. Dependencies are defined in package.json, and if our project requires them, Browserify will bundle these dependencies with our JS. Take this package.json for example:

    /* package.json */
      "name": "hipApp",
      "description": "Showing off hip stuff",
      "dependencies": {
        "browserify": "~3.44.x",
        "gulp": "3.8.x",
        "react": "0.11.x",
        "underscore": "*"

    Once we run npm install, we’ll have modules like React and Underscore available to use in our project. Now we just require them in our project:

    /* app.js */
    var React = require('react');
    var myModule = require('./myModule');
    // ...

    Then we invoke Browserify:

    browserify --debug app.js > bundle.js

    And Browserify will include React from npm for us. Notice that it will even figure out which local modules to include. We included ./myModule which is another module in the same folder as app.js.

    Let’s compare this style of dependency loading with technologies such as AMD ,which is prominently implemented by RequireJS. They are both JS module definition APIs but with different implementations. Browserify falls in line with CommonJS which is suited for the server, and RequireJS falls in line with AMD which is suited for the browser. However, either can be used in either environment.

    What’s awesome about Browserify is that all NPM modules are available for our project, 86K and counting. Its modules also do not need to be wrapped in a define call.

    Though Browserify requires all the modules up front, which means needing a build step. AMD is asynchronous so modules can be lazily-loaded, and all that is needed is a page refresh. Though we can automate the Browserify build step with Gulp.

    Gulp: The Streaming Build System

    Gulp is a JS build system, like Grunt, that makes use of “streams”, or pipelining, and focuses on code-over-configuration. Build systems are usually set up to watch for changes to projects, and then automatically handling common build steps such as bundling, pre-compilation, or minification. Both Gulp and Grunt have tons of plugins to help with these things. Browserify is one such plugin.

    Let’s take a look at an example Gulpfile. It includes some facilities for React JSX files which we haven’t looked at yet, but it’ll come in handy later. Read the comments in the Gulpfile to follow along:

    /* gulpfile.js */
    // Load some modules which are installed through NPM.
    var gulp = require('gulp');
    var browserify = require('browserify');  // Bundles JS.
    var del = require('del');  // Deletes files.
    var reactify = require('reactify');  // Transforms React JSX to JS.
    var source = require('vinyl-source-stream');
    var stylus = require('gulp-stylus');  // To compile Stylus CSS.
    // Define some paths.
    var paths = {
      css: ['src/css/**/*.styl'],
      app_js: ['./src/js/app.jsx'],
      js: ['src/js/*.js'],
    // An example of a dependency task, it will be run before the css/js tasks.
    // Dependency tasks should call the callback to tell the parent task that
    // they're done.
    gulp.task('clean', function(done) {
      del(['build'], done);
    // Our CSS task. It finds all our Stylus files and compiles them.
    gulp.task('css', ['clean'], function() {
      return gulp.src(paths.css)
    // Our JS task. It will Browserify our code and compile React JSX files.
    gulp.task('js', ['clean'], function() {
      // Browserify/bundle the JS.
    // Rerun tasks whenever a file changes.
    gulp.task('watch', function() {, ['css']);, ['js']);
    // The default task (called when we run `gulp` from cli)
    gulp.task('default', ['watch', 'css', 'js']);

    Just install the NPM dependencies, run ./node_modules/.bin/gulp, and it handles everything for us in the background. Our files are watched with, tasks are automatically run, and things are cleanly accomplished in streams and pipelines. Whenever we modify any JS/CSS, we can can refresh in the browser just as if we were using AMD.

    Whether to use Grunt or Gulp is a matter of preference. Both have tons of modules available, though Gulp is a bit newer. Grunt is done more through configuration whereas Gulp is done more through code and streams. Though Gulp can be a bit faster as it does not require intermediary files to accomplish its tasks. So with our build system in place, let’s head to the big show: React.

    React: Declarative and Reactive Components

    React is a JS library from Facebook for building reusuable web components. It’s not a full MVC framework like AngularJS; React focuses on view rendering of components making no assumptions about framework, and it can plug in to most projects smoothly.

    Facebook says React was made to build large applications with data that changes over time. Facebook wanted something that didn’t take over the whole application. They could mix in components that could be integrated with legacy components. If you’d like some convincing, Pete Hunt, one of the authors of React, wrote some arguments for React on Quora.

    Rather than imperative one-way data binding as in traditional applications or two-way data binding as in Angular, React implements a one-way reactive data flow. Rather than manually registering listeners and handlers to update the DOM, or having to set up linking functions and data bindings, React’s components are declaratively defined and automatically re-render when its data changes. Like a function, data goes in, components come out.

    For convenience, let’s take a look at an example based off of React’s homepage, which simply displays a name:

    /** @jsx React.DOM */
    var React = require('react');  // Browserify!
    var HelloMessage = React.createClass({  // Create a component, HelloMessage.
      render: function() {
        return <div>Hello {}</div>;  // Display a property.
    React.renderComponent(  // Render HelloMessage component at #name.
      <helloMessage name="John" />,

    You may have noticed, there’s some mark-up in our Javascript. React features syntatical sugar called JSX. It needs to be compiled into JS, which’ll automatically be done with our Gulpfile from earlier through the Reactify plugin. Though React also has a JSX compiler if we wanted it. Note that JSX is not required; React has normal JS APIs, but where’s the fun in that?

    Components are created with createClass. Like functions, components can take in arguments during rendering in the form of props. In the above example name="John" is passed into the component and is then referenced by {}. Note that components can be made up of only one Node. If we wish to have multiple DOM nodes, they must all be wrapped under a single root node.

    Along with taking input data through props, a component can have an internal and mutable state as accessed through this.state. Here’s another example, this time of a timer, based off of React’s homepage:

    /** @jsx React.DOM */
    var React = require('react');
    var Timer = React.createClass({
      getInitialState: function() {  // Like an initial constructor.
        return {
            seconds: 0
      incrementTimer: function() {  // A helper method for our Timer.
        this.setState({  // Use setState to modify state.
            seconds: this.state.seconds + 1  // Never modify state directly!
      componentDidMount: function() {  // A method run on initial rendering.
        setInterval(this.incrementTimer, 1000);
      render: function() {
        return (
          <div>Seconds Elapsed: {this.state.seconds}</div>
    React.renderComponent(<timer />, document.getElementById('timer'));

    We have a setInterval modifying our component’s state which triggers a refresh every 1000ms. Though in more practical applications, the state more likely be modified through user input or through data coming in via XHR rather than through a simple interval.

    And those are some of the basics of React. If reusuable declarative components and reactive rendering hits you as something that would sound perfect in your project, you can head to Getting Started with React. Best of luck to your development. Whether you decide to use these tools or not, it is always advantageous to know your options.

  9. Time to get hacking – Introducing Rec Room

    It’s no secret that the best frameworks and tools are extracted, not created out of thin air. Since launching Firefox OS, Mozilla has been approached by countless app developers and web developers with a simple question: “How do I make apps for Firefox OS?” The answer: “It’s the web; use existing web technologies.” was—and still is—a good answer.

    But if you don’t already have an existing toolchain as a web developer, I’ve been working on extracting something out of the way I’ve been creating web apps at Mozilla that you can use to write your next web app. From project creation to templating to deployment, Mozilla’s Rec Room will help you create awesome web apps in less time with more ease.

    Rec Room is a Node.js utility belt you can wear to build client side web apps. It includes:

    • Brick to add components like appbars and buttons to your UI.
    • Ember for your app’s controllers, models, and views.
    • Handlebars to write your app’s templates.
    • Grunt to run the tasks for your app, including building for production.
    • I18n.js to localize your app.
    • Mocha to test your app.
    • Stylus to write your CSS.
    • Yeoman to scaffold new code for your app’s models and templates.

    In this post I’ll walk through how to create a simple world clock web app with Rec Room, how to deploy it, and how you can try out Rec Room for yourself.

    Where Does Rec Room Come From?

    Much of Rec Room came from a recent rewrite of the HTML5 podcast app. I started working on this app well over a year ago, but its original version wasn’t as easy to work on; it had a lot of global state and a lot of by-hand data-binding. I liked the look of Ember for app development, but back when I started it didn’t quite feel mature enough. These days it’s much better, and I’ve tweaked it in Rec Room to work perfectly without a server.

    I tried to take the best from that system and extract it into a set of tools and documentation that anyone can use.

    Create your own Rec Room app

    Rec Room has just recently been extracted from my experiences with Podcasts; it hasn’t been tested by more than a handful of developers. That said: we’d love your help trying to build your own app for Firefox OS using these tools. They integrate well with tools you probably already know and use–like Node.js and Firefox’s own Web IDE.

    To get started, install Rec Room using Node.js:

    npm install -g recroom

    Clock App

    We’ll create a simple clock app with (minimal) time zone support for our example. The app will let you have a clock and compare it with a few time zones.

    The recroom binary is your entry point to all of the cool things Rec Room can do for you. First, create your app using recroom new world-clock. This creates the basic app structure. To see the basic app skeleton that Rec Room creates we can now enter that directory and run our app: cd world-clock and then type recroom run. The app will open in your default browser.

    First, we’ll add the current time to the main tab. Rec Room supports Ember’s MVC app structure, but also offers simple “pages” for a controller without a 1:1 relationship to a model. We’ll generate a new page that will show our actual clock:

    recroom generate page Clock

    We can edit its template by opening app/templates/clock.hbs. Let’s change clock.hbs to include the variable that will output our local time:

    <h2>Local Time: {{localTime}}</h2>

    That won’t do much yet, so let’s add that variable to our ClockController, in app/scripts/controllers/clock_controller.js:

    WorldClock.ClockController = Ember.ObjectController.extend({
        localTime: new Date().toLocaleTimeString()

    You can see that any property inside the controller is accessible inside that controller’s template. We define the 1ocalTime property and it gets carried into our template context.

    Now our clock app will show the current local time when we navigate to http://localhost:9000/#clock. Of course, it just shows the time it was when the controller was initialized; there is no live updating of the time. We should update the time every second inside the controller:

    WorldClock.ClockController = Ember.ObjectController.extend({
        init: function() {
            // Update the time.
        // Run other controller setup.
        updateTime: function() {
            var _this = this;
            // Update the time every second.
                _this.set('localTime', new Date().toLocaleTimeString());
            }, 1000);
        localTime: new Date().toLocaleTimeString()

    Now we can go to our clock URL and see our clock automatically updates every second. This is thanks to Ember’s data-binding between controllers and templates; if we change a value in a controller, model, or view that’s wired up to a template, the template will automatically change that data for us.

    Adding Timezones

    Next, we want to add a few timezones that the user can add to their own collection of timezones to compare against local time. This will help them schedule their meetings with friends in San Francisco, Buenos Aires, and London.

    We can create a timezone model (and accompanying controllers/routes/templates) with the same generate command, but this time we’ll generate a model:

    recroom generate model Timezone

    We want each timezone we’re to include in our app to have a name and an offset value, so we should add them as model attributes. We use Ember Data for this, inside app/scripts/models/timezone_model.js:

    WorldClock.Timezone = DS.Model.extend({
        name: DS.attr('string'),
        offset: DS.attr('number')

    Next we’ll want a list of all timezones to offer the user. For this we’ll grab a copy of Moment Timezone. It’s an awesome JavaScript library for dealing with dates and times in JavaScript. We’ll install it with bower:

    bower install moment-timezone --save

    And then add it to our app inside app/index.html:

    <!-- build:js(app) scripts/components.js -->
    <!-- [Other script tags] -->
    <script src="bower_components/moment/moment.js"></script>
    <script src="bower_components/moment-timezone/builds/moment-timezone-with-data-2010-2020.js"></script>
    <!-- endbuild -->

    Adding that tag will automatically add moment-timezone-with-data-2010-2020.js to our built app. We’ll add a tab to the page that lets us edit our timezones, on a different screen than the clocks. To add a tab, we just need to open app/templates/application.hbs and add a tab. While we’re there, we’ll change the main tab from the useless {{#linkTo 'index'}} and point it to {{#linkTo 'clock'}}. The new application.hbs should look like this:

          <h1>{{t app.title}}</h1>
            {{#link-to 'clock'}}Clock{{/link-to}}
            {{#link-to 'timezones'}}Timezones{{/link-to}}

    Side note: notice the root URL points to a useless welcome page? We probably want the default route to be our ClockController, so we can set the index route to redirect to it. Let’s do that now, in app/scripts/routes/application_route.js:

    WorldClock.ApplicationRoute = Ember.Route.extend({
        redirect: function() {

    Interacting with Timezone models

    We’ll keep things simple for our example and allow users to select a timezone from a <select> tag and add it with a button. It will show up in their list of timezones, and they can delete it if they want from there. The clock tab will show all times. First, we’ll add our timezone data from Moment.js into our TimezonesController in app/scripts/controllers/timezones_controller.js. We’re also going to implement two actions: “add” and “remove”. These will be used in our template:

    WorldClock.TimezonesController = Ember.ObjectController.extend({
        init: function() {
            var timezones = [];
            for (var i in {
          this.set('timezones', timezones);
      selectedTimezone: null,
      actions: {
          add: function() {
              var timezone ='timezone', {
                  name: this.get('selectedTimezone').name,
                  offset: this.get('selectedTimezone').offset
          remove: function(timezone) {

    So we create a list of all available timezones with offsets. Then we add methods that allow us to add or remove timezones from our offline data store. Next we modify the timezones template in app/templates/timezones.hbs to use the actions and variables we created. All we need to utilize these variables is the Ember SelectView and the {{action}} helper to call our add and remove methods:

    <h2>Add Timezone</h2>
    <p>{{view Ember.Select content=timezones selection=selectedTimezone
           optionValuePath='content.offset' optionLabelPath=''}}</p>
    <p><button {{action add}}>Add Timezone</button></p>
    <h2>My Timezones</h2>
      {{#each model}}
        <li>{{name}} <button {{action remove this}}>Delete</button></li>

    Now we have a Timezones tab that allows us to add and remove Timezones we want to track. This data persists between app refreshes. The last thing we need to do is show these times relative to our local time in our clock tab. To do this we need to load all the Timezone models in the ClockRoute. They’re automatically loaded in the TimezonesRoute, but it’s easy to add them in the ClockRoute (in app/scripts/routes/clock_route.js):

    WorldClock.ClockRoute = Ember.Route.extend({
        model: function() {
            return this.get('store').find('timezone');

    Because of the way our Ember app is wired up, we load all our models in the route and they are sent to the controller once the data store has asynchonously loaded all of the models. The request to find('timezone') actually returns a Promise object, but Ember’s router handles the Promise resolving for us automatically so we don’t have to manage callbacks or Promises ourselves.

    Now we have access to all the user’s Timezones in the ClockController, so we can make times in each timezone the user has requested and show them in a list. First we’ll add each Timezone’s current time to our ClockController in app/scripts/controllers/clock_controller.js using Moment.js:

    WorldClock.ClockController = Ember.ObjectController.extend({
        updateTime: function() {
            var _this = this;
            // Update the time every second.
                _this.set('localTime', moment().format('h:mm:ss a'));
                _this.get('model').forEach(function(model) {
                              moment().tz(model.get('name')).format('h:mm:ss a'));
            }, 1000);
        localTime: moment().format('h:mm:ss a')

    Our final app/templates/clock.hbs should look like this:

    <h2>Local Time: {{localTime}}</h2>
      {{#each model}}
        <h3>{{name}}: {{time}}</h3>

    And that’s it! Now we have an offline app that shows us time zones in various places, saves the data offline, and updates every second without us having to do much work!

    Command Line Tools

    The old Podcasts app used a (rather awful) Makefile. It wasn’t very useful, and I don’t think it ran on Windows without some serious effort. The new build system uses Node so it runs comfortably on Windows, Mac, and Linux. Commands are proxied via the recroom binary, also written in Node, so you don’t have to worry about the underlying system if you don’t need to modify build steps. recroom new my-app creates a new app; recroom serve serves up your new app, and recroom generate model Podcast creates a new model for you.

    To build your app, you just need to run recroom build and a version with minified CSS, JS, and even HTML will be created for you in the dist/ folder. This version is ready to be packaged into a packaged app or uploaded to a server as a hosted app. You can even run recroom deploy to deploy directory to your git repository’s GitHub pages branch, if applicable.

    See the app in action!

    This entire sample app is available at and the source code is available on GitHub.

    Try Using Rec Room for Your Next Web App

    You can try out Rec Room on Github. Right now some docs and tools are still being abstracted and built, but you can start building apps today using it and filing bugs for missing features. We’d really love it if you could give it a try and let us know what’s missing. Together we can build a cohesive and polished solution to the all-too-common question: “How do I build a web app?”

  10. JavaScript Error- and XHR Log Recording With Every Bug Report

    Let’s start with a story. A user story:

    A friend of mine called me in the middle of the day with a very strange request. He told me

    “Could you come over and help me to fill-in a form”.

    I was surprised as filling forms is the easiest thing to do online, isn’t it? Even for not so-tech-savvy people.

    So I went to my friend’s home and surprise, it wasn’t so easy! It took me 25 min to debug what was wrong with this website (a government one, in Bulgaria). The problem was missing validation (via XMLHttpRequest).

    Of course, I called the agency, expecting everything to go to /dev/null/, but surprisingly they were interested in the problem, so I spent another 25 min explaining the problem and sending them all data they needed. These included:

    1. Screen Size
    2. Browser and OS version
    3. Where exactly the problem occurs
    4. Javascript errors and XHR Logs (pasted in an email)
    5. Plugins installed on my friend’s browser

    etc, etc, etc … you know what I am talking about.

    It was exhausting.

    The perfect bug report

    Let’ step aside from the story and think more like developers. What a developer will need to fix the problem quickly, WITHOUT asking the user difficult questions:

    • Screen size, plugins, installed on your browser, URL where the problem happened, OS and Browser version
    • A visual and annotated screenshot showing where exactly is the problem and how it looks like through the user’s eyes with all steps on how to reproduce the bug.


    Wait, something is missing.

    The worst thing about most error reports from users is that they happen on the client-side, in front-end javascript, a cruel, cruel place, far away from the developer trying to fix them.

    Agreed? That’s why a perfect bug report should contain something else – a browsable JavaScript error- and XHR-logs recorder.


    Let’s Talk Code: Recorded JavaScript Errors

    The Usersnap Console Recorder saves every kind of JavaScript error. You can browse through the web developer console in the Usersnap dashboard, as if you would sit right on your user’s browser!

    Every error / log contains a NTP synced timestamp, a full stack including JavaScript source files and line numbers and formatting like the developer console you already know from Firebug

    Every debug log issued by console.log,, console.warn or console.error gets properly formatted (including recursive object/array formatting and browsing).

    Guaranteed no [object Object] hell during debugging!

    Accessing Properties of Undefined/Null Objects

    First example which happens quite often in the wild: a fixed element should be aligned by another element by using the top property during scrolling.

    However, due to a markup rework, the element #inexistent does no longer exist. This leads to offset() returning null and the property top can no longer be accessed:

    function clicky() {"Accessing a property of an undefined object");
        console.log("calculating scroll top %d", $('#inexistent').offset().top);

    Calling Methods of Undefined Objects

    Another rework case here: One tries to call a method on an undefined object.

    function clicky2() {"Calling a method of an undefined object");

    Plain Exceptions

    Sometimes you even know during development that something can break – wouldn’t it be great to know it when it actually breaks?

    function clicky3() {"Throwing an exception");
        throw "Version Mismatch!";

    XHR Errors

    Sometimes, XHRs deliver errors (like 404 Not Found or 500 Internal Server Error). Most of the time, such errors lead to bugs which are very hard to reproduce.

    function clicky4() {"404 on XHR");
            "url": "non_existing.php"

    Cross-Origin XHRs are troublesome. Image someone changes the CORS header and your cross origin XHR does no longer work from one day to another.

    function clicky5() {"Cross-Origin on XHR");
            "url": ""

    XHR and Time Tracking

    Recording the Steps During a Checkout

    Conversion rates are key in most businesses. Any obstacle for the user can lower your rates – e.g. it takes too long to load a page or you even have an error during checkout.

    This short example shows a standard click handler which calls getcheckout.php via XHR. Unfortunately, the second XHR (confirm.php) fails and throws a JavaScript exception. That’s nice, but: the user does not get any feedback. The page just stalls.

    function checkout() {
        console.log("check out clicked!");
            url: "getcheckout.php",
            dataType: "json"
        }).done(function(data) {
            console.log("Checked out: %o", data);
    function confirm() {
            url: "confirm.php"
        }).error(function() {
            throw "internal server error on confirm!";

    Additionally, you will get a full synced time frame of your user’s action (regardless if the time on the user’s browser is correct or not!). The full formatting support for objects (console.log(“Checked out: %o”, data);) is super convenient for debugging.


    Now every developer can have the superpower of understanding what the problem is even on the client-side and stop worrying about “It does not work. Fix it ASAP!” type of communication.

    And now every user will be able to report the issues better, because he/she needs just to press one button to report and issue, using the tools he/she knows well, and the magic will happen in the background.

    Free licenses for FOSS projects

    We at Usersnap support and believe in the FOSS (Free/Libre and Open Source) movement and that’s why Usersnap is free (as in free beer) for any FOSS project to use.

    We utilize a number of open source components like nginx, python, rabbitmq, angular and giving back to the community + improving the quality of your projects is a way to say “Thanks”

    Your project must meet all of the following criteria to be approved:

    • The project is licensed under a license approved by the Open Source Initiative.
    • The project source code is available for download.
    • Your open source project has a publicly accessible website.

    Apply here.