BuiltByCactus

Engineering Handbook

Performance

Performant JavaScript is a massive part of JS development at Built By Cactus. Badly written JS can not only slow a site down significantly, but also crash browsers etc.

For this reason, there are a couple of rules we follow:

Only Load Things You Need

If you need jQuery, then by all means load jQuery, but don’t pull in a million different plugins and extra libraries for it, unless you need them.

This works in development too, if you switch between libraries to find one that works better for you, don’t forget to remove the old ones!

Cache DOM Selections

Something a lot of people do in JavaScript and especially with jQuery, is to not cache its selector. This means that the library has to re-select the elements every time it’s fired, wasting precious time!

// Uncached
var $hideButton = jQuery('.hide-button');

$hideButton.on('click', function () {
  var $menu = jQuery('#menu');
  $menu.hide();
});

// Cached

var $menu = jQuery('#menu');
var $hideButton = jQuery('.hide-button');

$hideButton.on('click', function () {
  $menu.hide();
});

DOM Selectors

This is pretty simple. If you’re writing code that will need to be hooked with JS, don’t use an ID. Use a class prefixed with js- so we know it’s a javascript selector.


<div class="sidebar sidebar--orange sidebar--open">
    <button class="sidebar__button js-sidebar__button" id="sidebar_close">Close Sidebar</button>
</div>

<script>

    // No
    jQuery('#sidebar_close');

    // No
    jQuery('.sidebar__button');

    // Yes
    jQuery('.js-sidebar__button');

</script>