Tips for optimizing javascript performance

Zuno Studios - Dev with David

Here are some javascript optimization tips I've picked up that can help optimize your websites for better performance.

Like it or not javascript is becoming a bigger part of the web allowing us to build more complex experiences and make browsers do things that were unimaginable just a few years ago.

Put your code at the bottom

This is a bit counter intuitive because we're often trained to put stuff like <script> in the <head> of a page.

Here's the reason for putting code at the bottom of the page: when a page loads, it loads everything on different threads so we can have multiple downloads simultaneously. Javascript, however, blocks all other threads while it is downloading stalling the page load.

If javascript is placed at the bottom (right above </body>), the visual content of a page will load first so the user won't have to look at a blank screen waiting.

jQuery is heavy

Thankfully, right now common javascript libraries are around 40KB. And in this day in age, everyone has fast internet right? Well, no. In America, even though most of us have broadband to connect to the internet, we can still get a poor connection on our mobile devices.

So, why did I mention jQuery? Don't get me wrong, I love jQuery but too often I see people including it to add a bit of functionality, like a dialog box. Let's say we have to display a dialog when we click a link. Compare these two:

// jQuery
    function () { 
// Vanilla JS
document.getElementById('#mylink').onclick = 
    function () {

The jQuery code is smaller and the difference is only 30 bytes. But, jQuery itself adds another 40,000 bytes. That could be the extra second that convinces the user to leave your page. Here is where you can see the how to implement some common jQuery snippets in Vanilla JS.

Be careful with memory

Many libraries make it much easier to make web apps from the ground up, providing some abstractions that allow us to keep focusing on creating a great app. Then, we look at memory usage for our page. It's very easy to spawn a dialog box for everything we want to edit or just append and clone elements everywhere. Unfortunately, it all adds up, and this hurts even more for mobile. A major cause of this is instantiating many objects. For example, if you can reuse a CKeditor instance, be sure to do so. Having too many on a page will indeed bog a page down and like I've mentioned before, speed is important.

Ultimately, these tips aren't absolute and it really depends on what you're doing.

Keeping that in mind, I'll pass along some wise words I was told a while back: Be patient with people, not with computers.