RSS Feed for Medianic

The Essentials of Zepto.js



/

Modern JavaScript libraries are quite the behemoths — just take a look at jQuery. When you’re creating a mobile app, or even just targeting modern browsers, a library that’s much more svelte and nimble becomes a tastier proposition.

Today, we’re going to look at one such library, named Zepto.


The Issue With Mixing Desktop Libraries and Mobile Devices

One thing that has snuck past most radars has been the rise of mobile devices.

See, the internet, and the technology that powers it, has grown in leaps and bounds over the past years. We moved from static sites to web applications to dynamic web applications and then to real time, hyper responsive, thingamabob apps of today. One thing that has snuck past most radars has been the rise of mobile devices.

Think about it: a lot of us use smart phones and use it for browsing on a constant basis. Even at home, a non-trivial portion of my circle has adopted a tablet device for casual surfing and email. While this influx of devices is good from an exposure point of view, it isn’t without its caveats.

Instead of thinking of these devices as display constrained like consumers do, we, as developers, need to think of them in terms of resources and bandwidth. Not all them sport a hyper quad gajillion Ghz CPU or come with oodles of memory. And let’s not even get started with the bandwidth. A big portion of the browsing population is still stuck on these infernal excuses for a mobile internet connection.

I think you see where I’m going with this. Big, monolithic libraries like jQuery or Prototype definitely have their place but for this mobile era, I think there’s a place for something that’s a lot more nimble. And a lot of developers seem to agree with me.


All the Code to Make a Library Work Across Browsers Adds Up

Another big issue that I failed to mention is that contemporary libraries do a lot of cross browser stuff. In fact, a big draw of jQuery, initially, was how it abstracted away a lot of the cross browser quirkiness that front end developers had to work around. Even now, jQuery does a lot of heavy lifting under the hood to make sure nothing breaks in different browsers.

But if you’re a developer looking to cater to only contemporary devices, do you really need all this, dare I say, cruft? The short answer is no. By cutting out unnecessary code, you both:

  • eke out more performance since there’s fewer lines of code for the browser to parse and
  • make your file smaller in size, which helps with the bandwidth constrained mobile devices.

Think that this issue is overblown? Here’s a random blob of code from jQuery’s source:

isPlainObject: function( obj ) {
		// Must be an Object.
		// Because of IE, we also have to check the presence of the constructor property.
		// Make sure that DOM nodes and window objects don t pass through, as well
		if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
			return false;
		}
....

Or something a little more esoteric:

// Perform a simple check to determine if the browser is capable of
// converting a NodeList to an array using builtin methods.
// Also verifies that the returned array holds DOM nodes
// (which is not the case in the Blackberry browser)
try {
	Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType;

// Provide a fallback method if it does not work
} catch( e ) {
	// The intended fallback
}
....

This may look fairly trivial but keep in mind this tends to adds up. If you’re only going to target modern browsers, either on desktops or mobiles, then there is no real need for all these additional checks and hacks. By cutting down your intended browsers, you win on both bandwidth and performance!


So What’s Zepto’s Deal?

I hear you guys saying “Enough buildup! Tell us about the darn library already!”. So let’s get to it.

Zepto, as the title spoiled it for you, is a mobile JavaScript framework that rectifies both of the issues mentioned above. It has a very small code base and is feather weight at around 8kb.

It manages to be so svelte by mostly cutting out the cross browser stuff. When it was created, the main focus was to support Webkit only. The mobile version of Webkit to be exact. Now, it’s been expanded to work with desktop browsers too — but only modern ones. No more klutzing around to make things work this IE6!

Zepto’s API is jQuery compatible. If you use jQuery, you already know how to use Zepto.

Another area where Zepto manages to be small is how it manages to avoid feature bloat. The core library doesn’t seem to include any extraneous functionality. Even the AJAX and animation functionality are available as separate modules, should the need arise. For users that primarily use libraries for DOM traversal and manipulation, this is an utter god send.

And, oh, did I mention Zepto’s main party piece? Zepto’s API is jQuery compatible. If you use jQuery, you already know how to use Zepto.


Are Zepto and jQuery Interchangeable?

Yes and no. Depends is a more apt answer.

Yes because Zepto’s core API mimics jQuery to a large extent. In order to make it easy to use and dramatically reduce the learning curve, Zepto emulates jQuery’s API. Most of the oft used methods, like DOM manipulation, are named pretty much the same and have the same parameters in the same order. The method signatures are the same, for the engineers out there.

Let’s look at a small example:

$( #element ).html("Hey! Are you on the GW2 beta?");

Looks familiar? It should. This is the exact same code you’d use with jQuery to change the HTML of an element. As I mentioned, this isn’t limited to just this method. Most DOM operations are built the same way along with your utilities, like AJAX.

On the flip side, the API isn’t a 100% match. Zepto forgoes some methods present in jQuery that’s liable to break your code. And just as importantly, since Zepto is a subset of jQuery, you’ll probably miss out on specific functionalities that are built in — Deferred is a fine example. You simply can’t swap out jQuery with Zepto and expect everything to work.

And for me, the biggest hurdle are the methods that have been copied from jQuery but have a different signature and feature set. It becomes a little frustrating when you think you’re using a method right but you aren’t. The clone method’s ability to copy event handlers is a good example. Without looking at the source, I really wouldn’t have found this out.


Exploring the Core API

If you’ve worked with jQuery before, everything below should be a snooze fest.

Enough chit chat, let’s dive into some code now. As with a lot of modern libraries, DOM traversal and manipulation is a core feature that everyone wants to perfect. Since the API and overall functionality is very similar to jQuery, I think you can safely assume everything is top notch.

Let’s take a look at some common DOM related functionality.

Modifying the HTML contents of a container

This is the bread and butter of DOM operations: reading or changing the HTML contents of an element. With Zepto, it’s as simple as calling the html method on the container, and passing in the new HTML, if needed.

For example, this obtains the HTML of an element and stores it in a variable.

var containerText = $( #element ).html();

Or if you want to change it to something else:

$( #element ).html("Hola there!");

Pretty simple, right?

Prepend/Append an Element to a Container

As with jQuery, Zepto makes use of the append and prepend methods. And the invokation remains the same as well.

$( #element ).append("<p>This is the appended element.</p>");

// or

$( #element ).prepend("<p>This is the appended element.</p>");

Events

Events are the backbone of any modern application and Zepto provides you with a bunch of easy to use methods to get your job done. The bulk of the work is done through the on method.

$( #element ).on( click , function(e){
   // Your code here
});

Easy to read and easy to parse. If you’re feeling old school and feel like using bind, delegate or live methods, don’t. Just like with jQuery, they’re deprecated here.

AJAX

Any modern low level library needs to provide an easy to use wrapper around AJAX and Zepto doesn’t let you down here. Here is an example of a super simple AJAX request.


$.ajax({
  type:  POST ,
  url:  /project ,
  data: { name:  Super Volcano Lair  },
  dataType:  json ,
  success: function(data){
    // Do some nice stuff here
  },
  error: function(xhr, type){
    alert( Y U NO WORK? )
  }
});

Things might look a little complicated but what we’re doing can be boiled down to:

  • Creating the AJAX object and passing it options.
  • In the options, specifiy that we’d like to do a POST request. The default is GET, I imagine.
  • Specify the URL to POST to.
  • Specify the data that needs to be sent to the server. As you can see, I’m laughing maniacally and trying to create my own super villain lair.
  • Specify methods that will be triggered when the request succeeds or fails. This way, we can update the UI whatever happens.

As with jQuery, there are separate method for a GET or POST request or ones to merely load up some web content.

Animations

What will the world come to without a few animations? Zepto exposes the almighty animate method that should handle most of your animating needs.

$( #element ).animate({
  opacity: 0.50, top:  30px , color:  #656565 
}, 0.5)

We’re basically selecting the element to be animated, invoking the animate method and specify the properties to be animated as well as the time it should take to finish animating. Zepto does the rest.

Or if you just need to show and hide an element, the toggle should work just fine.

I think you get the point here — Zepto’s DOM, animation and events API emulates that of jQuery to a large extent. And as we all know, jQuery is darn good with those things. If you’ve worked with jQuery before, you shouldn’t face too much trouble here.


A Look at the Touch Events and Other Niceties

Zepto does provide you with a few touch specific events that you can leverage in your apps. These include:

  • swipe — Handles your typical swipe motion. There are also separate events for different directions, like swipeLeft.
  • tap — Triggered in response to a generic tap action.
  • doubleTap — Obviously, this handles double taps.
  • longTap — It’s triggered when an element is tapped on for more than 750ms. There doesn’t seem to be a straightforward to change this delay though.

Here’s a quick example, delightfully swiped from Zepto’s documentation.

<ul id=items>
  <li>List item 1 <span class=delete>DELETE</span></li>
  <li>List item 2 <span class=delete>DELETE</span></li>
</ul>

<script>
// show delete buttons on swipe
$( #items li ).swipe(function(){
  $( .delete ).hide()
  $( .delete , this).show()
})

// delete row on tapping delete button
$( .delete ).tap(function(){
  $(this).parent( li ).remove()
})
</script>

When a list item is swept, every other list element’s delete button is hidden and only the current’s is displayed. Tapping a delete button removes that button’s parent li item to be removed from the DOM.

This should be fairly similar to how you generally handle events, except you’ve binding your handlers to different events, that’s all.


Wrapping Up

Considering what and whom I develop for, this is perfect for me; but as it always is, your mileage may vary.

Well, that’s about almost all there is to Zepto. At it’s core, it was meant to be a lean, cruft free version of jQuery that could be used on mobile devices. Over time, it has morphed into a lean library that does away with supporting archaic browsers.

Considering what and whom I develop for, this is perfect for me; but as it always is, your mileage may vary. You may be locked into using jQuery plugins that require non-trivial modifications to make it work under Zepto or just have more faith in jQuery.

Either way, you really need to give Zepto a try to see how it fits in with your workflow before writing it off. I did and I love it!

Well, that’s all from me today. Let me know what you think in the comments below and thank you so much for reading!



RSS Feed for Medianic
Medianic Web Design Services