React Asset Loader

This is simple react component for loading assets. It allows you to load from a single asset to multiple assets without affecting the pageload speed. You can also add custom classes, attributes and callback functions.

Concept

We all get scared of heavy websites, there are tons and tons of articles telling us why we shouldn’t build websites using heavy assets like videos or gifs. But sometimes, you just need to, sometimes you just need to build a cool interactive experience with videos, or so something cool with gifs, or a long page with lots of high quality images, etc. This component is precisely for that.

How it works.

This component allows you to load all the assets you want without affecting the pageload speed, this is because it will load the page and then it will start loading all the assets, it adds a <div className=”loading”></div> wrapper while it’s loading the asset so you can have a nice custom loader, when the assets are loaded it will replace the loading wrapper with the actual assets.

Install.

npm install react-asset-loader --save-dev

Or just grab the component LoadAsset.js directly.

Usage

Load a single asset.

<LoadAssets assets={[{"uri":"/static/images/asset.jpg"}]} />

Load multiple assets. When you need to load more than one asset for one experience. It will be loadad after all the assets passed are loaded.

<LoadAssets assets={[{"uri":"/static/images/video1.mp4"}, {"uri":"/static/images/video2.mp4"}]} />

// or also 

var videos = [ {"uri":"/static/images/video1.mp4"}, {"uri":"/static/images/video2.mp4"} ]

Adding classes.

You can add classes to each asset you pass to the component.

<LoadAssets assets={[{"uri":"/static/images/asset.jpg", "className":"class1 class2"}]} />

Adding attributes. You can also add attributes to each asset you pass to the component.

<LoadAssets assets={[{"uri":"/static/images/video.mp4", "attributes":[{"autoPlay":"true"}, {"loop":"true"}]}]} />

// or also 

var video = [{ "uri":"/static/images/video.mp4", "attributes": [ {"autoPlay":"true"}, {"loop":"true"} ] }]

Custom onLoad callback.

You can have a custom callback for when your assets are loaded.

<LoadAssets onLoad={this.onCoolVideoLoaded} assets={[{"uri":"/static/images/video.mp4"}]} />

Examples

You’ll need a webserver in order to run the examples (CORS). The quickest way to do this is just run this on the examples folder of the project:

python -m SimpleHTTPServer

Link

Github
https://github.com/juancabrera/react-asset-loader

NPM package
https://www.npmjs.com/package/react-asset-loader

Tweet about this on TwitterShare on FacebookShare on Google+Share on Reddit

Using ES6 modules in the browser.

There are a lot of information about Gulp, not so much for ES6 and just a very few articles about how to implement ES6 modules (for the browser) properly.

On my last project I was using Gulp + ES6 and I had to spent some time figuring out how to get ES6 modules working properly. This is how I finally did it without using Browserify or any AMD loader.

My first attempt was to use gulp-es6-transpiler (that basically is a wrapper for es6-transpiler) but it doesn’t support modules, then I took a look to gulp-es6-module-jstransform but it only transpile to CommonJS, meaning that we’ll need to use Browserify, then I tried Traceur (from Google) and it has two options for browser modules, one is ‘AMD’ (meaning that we’ll need to use RequireJS or similar) and ‘inline’ that basically what it does is generate one file with all the transpiled modules on it (which is the closet option to “native” ES6 modules).
The thing is that the ‘inline’ option works perfect if you are using the command line, but if you use the Traceur’s node API (like gulp-traceur) it’ll throw an error. [UPDATE] I’ve put this issue on their Github and finally got fixed, but then we realized that the transpile from the node API wasn’t generating the same output as the command line, so we finally decided to build a small Gulp plugin wrapper for the command line Traceur (Thanks Edward!)

Here is the plugin and this is how you can use it:

Install
Make sure you have installed Traceur globally:

npm install traceur --global

Install gulp-traceur-cmdline to your project:

npm install gulp-traceur-cmdline --save-dev

Usage

var gulpTraceurCmdline = require('gulp-traceur-cmdline');

gulp.task('gulpTraceurCmdline',function() {
  gulp.src("./source/styleguide/js/main.js")
    .pipe(gulpTraceurCmdline('/usr/local/bin/traceur', {
      modules : 'inline',
      out     : './dist/styleguide/js/main.js',
      debug   : false
    }))
});

 

Github: https://github.com/juancabrera/gulp-traceur-cmdline

NPM: https://www.npmjs.org/package/gulp-traceur-cmdline

Tweet about this on TwitterShare on FacebookShare on Google+Share on Reddit

My front-end codebase

After trying different front-end configurations in the past few months (Grunt or Gulp, HAML or Slim, ES6 modules or AMD modules, etc) I have finally found one that I’m pretty comfortable with (at least for a while). This codebase is using:

Next steps

Try and incorporate performance tools (like uncss, critical-path) and testing tools.

You can find the codebase on my Github (feel free to contribute if you like it): https://github.com/juancabrera/gulp-frontend-codebase.

Tweet about this on TwitterShare on FacebookShare on Google+Share on Reddit

Javascript 360

Almost a year ago I wrote a small Javascript method that takes a bunch of images (frames) and make with them a spinnable 360 with inertia that works for both desktop and mobile. I also tweaked it a little bit so it could work with a Leap Motion.

I want to retake this little project in order to make some improvements, mostly in performance, tweaking the inertia and probably adding native support for the Leap Motion. If you want to help, you are more than welcome 🙂

Demo: http://juancabrera.github.io/three60/
Demo with LeapMotion: http://instagram.com/p/fTSUreky5f/
GitHub Repo: https://github.com/juancabrera/three60

[UPDATED] Nov 13, 2014.

  • Fixed bugs with interaction.
  • Added RequestAnimationFrame.
  • Improved inertia.
  • Removed jQuery dependency.
Tweet about this on TwitterShare on FacebookShare on Google+Share on Reddit

The spring effect in JavaScript.

In the last weeks I was trying to figure out a way to make things scroll nicer and that doesn’t affect negatively the performance. When I start I didn’t know exactly what was the result I wanted, so after a few frustrated attempts coding something by my self I start looking for some sort of custom easing functions, how they works, etc. This is how I got to this blog about Physics and JavaScript, specifically to this article about car suspension (Hooke’s Law). And I thought it may works great on scrolling.

After trying several times to use this on scrolling I finally made my first successful attempt, and it was pretty much what I had in mind: http://code.juan.me/demos/springy/basic/html/. In the demo you can see on the left, the green squares are being “eased” with the spring effect, the one on the right has no easing (so you can see the difference).

Looking at the first attempt (and being an Android user) I realized there was something familiar with it, it took me a while to realize that it was exactly what the Messages App of iOS 7 does, so of course I couldn’t resist to do this: http://code.juan.me/demos/springy/messages/html/. And now we can say that Apple is using car suspension physics in some of their Apps (?).

I also wanted to try this in a sort of more real use case, so I made two more demos using a grid prototype, this one with images: http://code.juan.me/demos/springy/grid-prototype/html/ and this one more clean in white: http://code.juan.me/demos/springy/grid-prototype-2/html/

The Code

Note: I’ll only go through the parts of code related to the spring effect of the first demo, if you want to see more how the demo was made feel free to take a look at the full code.

var options  = {
    stiffness: 100,
    friction: 20,
    threshold: 0.03
}, 
inMotion = Array(false, false, false, false, false, false)

First at all we define the spring properties, the params “stiffness”  and “friction” talk by them self. The “threshold” option is basically how long you want to keep the spring working, so like if acceleration is equal or less than 0.03 it will stop. The “inMotion” array specifies which of the squares are currently in motion.

core.onScrolling = function(e) {
    lastScrollY = scrollY;
    scrollY = window.scrollY;

    for (var i = 0; i &lt;= 5; i++) inMotion[i] = true;

    if (!animating) {
        animating = true;
        requestAnimFrame(core.stepScrolling);           
    }
}

When the scrolling starts we set the flag of motion for each square in “true” and we also call “core.stepScrolling” using requestAnimFrame.

core.stepScrolling = function() {
    $.each($boxItems, function(i, v) {
        var $thisItem = $(v);

        if (inMotion[i]) {
            if (scrollY - lastScrollY &gt; 0) {
                acceleration[i] = (options.stiffness + (i * 5)) * ((scrollY + 50)  + (i * 40) - parseInt($thisItem.css("top"))) - options.friction * velocity[i];
            } else {
                acceleration[i] = (options.stiffness - (i * 5)) * ((scrollY + 50) + (i * 40) - parseInt($thisItem.css("top"))) - options.friction * velocity[i];
            }
            velocity[i] += acceleration[i] * frameRate;
            newTop[i] += velocity[i] * frameRate;
            inMotion[i] = Math.abs(acceleration[i]) &gt;= options.threshold || Math.abs(velocity[i]) &gt;= options.threshold;

            $thisItem.css({top: newTop[i]});
        } else {
            core.completeScrolling();
        }
    });
    if (animating) requestAnimFrame(core.stepScrolling);
}

Here we go through all the square elements, if it is still in motion we calculate and set the acceleration, velocity and new position for it. When the squares are not in motion we call “core.completeScrolling”.

core.completeScrolling = function() {
    for (var i = 0; i &lt;= 5; i++) {
        acceleration[i] = 0;
        velocity[i] = 0;
        inMotion[i] = false;
    }
    animating = false;
    cancelAnimationFrame(core.stepScrolling);
}

And finally, on “completeScrolling” we reset all our variables and stop the Request Animation Frame that was calling “core.stepScrolling”.

If you are kinda obsessed with motion and transitions I’m pretty sure you will love this. I think it’s amazing the great results and all the different uses you can get just digging a little bit on physics or math.

Update — Jan 27, 2014.

I put these demos in a GitHub repo because some people wanted to contribute with a few improvements in performance 🙂

https://github.com/juancabrera/demos 

Tweet about this on TwitterShare on FacebookShare on Google+Share on Reddit