ZeptoJS: Nice and fast

ZeptoJS is a lightweight Javascript library that mimics JQuery selectors and typical functionality, while being much smaller (~25KB, can go under 10KB GZipped). It was meant for mobile so works on most widely used platforms and its only major drawback is no support of Internet Explorer.

I have one micro-site to keep my bookmarks, really really simple: I manage the bookmarks by editing a C# array that when the page gets loaded renders the contents in this format:

<div id="bmarks">
<h3 id="0">__SECTION_NAME__</h3>
<p id="s0">
<a href="__URL__">_DESCRIPTION__</a>
<a href="__URL__">_DESCRIPTION__</a>
<a href="__URL__">_DESCRIPTION__</a>
</p>
<h3 id="1">__SECTION_NAME__</h3>
<p id="s1">
<a href="__URL__">_DESCRIPTION__</a>
...
</p>
...
</div>

Previously, I had additional markup and lots of "onclick" added to every section and item tags, plus no javascript library, only pure JS to toggle displaying one category, hiding another, and other fancy stuff.

The page weighted around 12KB and, while it was really fast loading with a lot of bookmarks, response when using it just after loading was not as good at my mobile phone as in the desktop. In my context this meant that my javascript either was slow due to lots of DOM elements (few hundreds only so unlikely) or due to having to attach and manage too many event handlers (one per bookmark, one per section in my original code).

This, combined with some DOM lookups that were redundant, were for sure the source of unoptimal performance in such a simple webpage.

Yesterday I decided to reduce a lot the markup, do more CSS styling for removing tags (like <br>), and reduce the Javascript to the minimun after adding ZeptoJS. I removed some visual stuff that really was not so interesting, like +/- icons before the section name (which I could have done with CSS too).

This is the resulting javascript I need to toggle displaying and hiding of sections:

$('#bmarks').on('click', 'h3', ToggleSection);
function
ToggleSection(eventData) {
$(
"p").each(function () { $(this).hide() });
$('#s' + eventData.currentTarget.id).show();
}

Keeping DOM lookups to the minimum with event delegation proved really easy to achieve, and toggle() function saved me some ifs and extra lines of code to handle the logic of hide/show.

Now the page weights ~50KB because I have inlined ZeptoJS library and CSS. With proper a caching header and unfrequently changing contents (as it is my scenario) this means a single HTTP request to fetch everything and then cached read from the browser onwards.

On my phone the first load feels equally faster under 3G (where latency downloading content sucks) but now the page is really really responsive. As it only keeps one event handler for the whole document's clicks feels way more responsive.

ZeptoJS: Nice and fast published @ . Author: