How To Improve JavaScript Performance

It’s worth it.

JavaScript is an integral part of every web page. While JavaScript helps us make applications more dynamic but it also has its own costs. A little bit of discipline can help you load the websites faster and interact faster with any device. Before we dive into how to improve the performance of JavaScript we will look at how it can affect your site and maybe even lead to losing users.

Cost Of JavaScript

1. Interactions with Host
All interactions between the browser and the user introduce unpredictability and increase performance lag. Well, it cannot be avoided completely but we can definitely keep it minimum.

2. Too Many Dependencies
Having too many poorly managed dependencies in the application can have a big impact on the performance. The users will have to wait for longer period especially the mobile users with low bandwidth.

3. Poor Event Handling
Using event handlers properly can improve the performance of the app to a great extent by reducing the depth of the call stack.

4. Inefficient or Unwanted Iterations
Loops increase the processing time of your application. Removing unwanted or inefficient loops seem to be the first step while optimizing your code.

Now that we have seen some of the problems that could affect the performance of your application, let’s dive into how to give your application’s JavaScript a performance boost.

10 Ways To Improve JavaScript Performance

  1. Use document.getElementById()

Using JQuery it becomes quite easy to select DOM elements using tags, classes or ids. But this approach involves several iterations as JQuery loops through DOM elements to find a match. You can speed it up by using document.getElementById()

// Using JQuery
var container = $(“#container”);
// Plain JavaScript
var container = document.getElementById(“container”);

2.Compress your files
Smaller the size of files faster it is to download them for the users, which results in faster performance. Use a compression method such as Gzip or Brotli to reduce the size of your JavaScript files

3.Minify

Minification refers to the removal of unwanted/cumbersome elements from our JavaScript source.

Unwanted refers to comments, semi-colons, whitespace etc. While cumbersome refers to shortening function and variable names, reducing an if-else into ternary etc. It can be achieved with build tools like UglifyJs, Google Closure compiler or online tools like JS Compress, JS minifier etc.

4.Use mouseup instead of click
Users interaction via mouse or keyboard fires several events in a specific order. It is better to bind your functionality with the mouseup event which fires before click event, this can provide performance boost especially in the older browser such as IE. This ensures that none of the interactions are missed if a user makes several mouse clicks in rapidly.

5.Cache as much as possible

Caching your files in browser helps to improve the loading time of the site both for previous visitors as well as for first time users. The browser uses the locally cached copy for any pages loaded after the initial one instead of fetching them over the network. Use JavaScript service workers to cache files for offline use. Going offline gives the application feel of desktop or mobile which gives the illusion of faster app.

6.Favor native functions and constructs
Rather than writing your own algorithms, it’s better to use native functions and constructs. ECMAScript provides lot of native functions like Math.floor() , Math.round(), String.prototype.match()and many others.

7. Use async and defer attributes
 async and defer are attributes can be added to script tags to make them either load asynchronously to the page or defer until the page has completely loaded. Using either of these attributes doesn’t block the DOM from rendering, which makes the application faster.

<! — load example.js asynchronously to the page →
<script src=”example.js” async></script>
<! — load example.js after the page has loaded →
<script src=”example.js” defer></script>

8.Recycle the DOM
If you look at Facebook, Instagram, Twitter and other sites that have infinite scrolling enabled then you can understand that more and more elements are getting added to the DOM. These can cause problems since we have to now query more elements. Therefore performance decreases and browser slows down by consuming RAM.

This problem can be solved by recycling DOM elements. Allocate some elements to use for displaying content to the DOM and when that elements exit the viewport, you take it back to the bottom.

9.Switch to HTTP/2

HTTP/2 is the latest version of HTTP protocol that provides some enhancements that will improve not only JavaScript performance but also improve the speed of the site in general. HTTP/2 is multiplexed which means that it handles multiple requests and responses simultaneously.

10.Animate with requestAnimationframe
Animations should ideally render at 60fps(or a frame every 16.667ms) which is just perfect for human eyes. JavaScript libraries like Anime.js and GSAP are helpful for creating quick animations, but if your JavaScript animations are still running slow, try using the requestAnimationFrame() method to get them up to speed. With requestAnimationFrame, we tell the browser to call a function to render a frame.

function moveLeft(){
// code to move the box to the left
}
window.requestAnimationFrame(moveLeft);

If you liked my article and if it was useful to you please don’t forget to give your claps. 👏