How to Write Faster and Lighter Code in JavaScript

How to Write Faster and Lighter Code in JavaScript

0 1635
JavaScript optimization

Who doesn’t want to build interactive websites that involve JavaScript for better user attention? Have you experienced the low responsive websites or applications, only to have nothing happen when you just tapped a link or scroll down? We are pretty sure all of us have been with this. JavaScript is still considered the most expensive resource we utilize for our mobile devices as it can delay interactivity in significant ways mostly byte-for-byte.

What’s the real mechanism behind it?

When a user is trying to access your site, they probably get a lot of files in the form of strips. Just by adding a quick JavaScript library or plugin you cannot really check how much code it is pulling in? To overcome this, many popular sites transfer megabytes of JavaScript to their web users on mobile devices. Sites today offer bundles of JavaScript user-interface components, client-side framework, polyfills and full libraries that sums up the code which definitely takes more time than needed.

You may still wonder why this happens. When you look up for any website, a request is sent to the server that returns some HTML which is being marked by the browser to discover the necessary code. Once this process is completed, the browser downloads and process these files. If you wish to be faster at JavaScript, then we need to have a fast network transmission along with the parsing, compiling and execution of the scripts. Also, the JavaScript is expensive as the resources on the web have different costs and even the processing costs are not the same.

Google’s V8 (Chrome, Node) are JavaScript engines which are specifically designed for the faster execution of huge applications for proper java development. If you care about the memory usage and performance, then you should be aware of what is going on in your user’s browser JavaScript engine behind the scenes.

How does JavaScript works in V8?

Firstly, a base compiler is present which parses your JavaScript code to generate native machine code for execution. The objects in V8 are presented in an object model or associative arrays in JavaScript as an internal type system for optimized lookups. The runtime profiler tracks hot functions along with the optimizing compiler that identifies the runtime profiler and performs inlining. It also supports deoptimization which can bail out the generated code for optimization. In the end, a garbage collector is present for memory management to perform accurate java development.

What can be done to increase JavaScript Performance?

We have seen the actual reasons to what causes hindrance in JavaScript performance to which we can check out some tips and tricks to boost it up.

Using HTTP/2 and Point references

The latest version of the HTTP protocol is recognized as HTTP/2 which has got some great enhancements to speed up your site in general. It utilizes multiplexing, allows multiple requests and responses at once to increase your performance. Also, you can cut down on DOM traversal trips by storing pointer references in browser objects.

If you do not wish to change your DOM or stop storing a reference to DOM and JQuery objects, you just need to create a page that can help speed everything up. With this, the HTML complexity also plays a crucial role to determine how long it takes to proceed the query or modify DOM objects. Eliminate the unnecessary <div> and <span> tags to double up the speed.

Buffer DOM and Compress your files

Every minor change in DOM can batch them up to prevent getting repeated screen rendering for any style change or modification you make. You can make a use of buffer to remove items from the DOM if you have scrollable DIVs which are not currently visible inside the viewpoint. Try some compression methods like Gzip or Brotli to reduce the JavaScript files as smaller files are easier to download and improve performance.

Add up post-load dependency managers and limit library dependencies

Few dependency managers like RequireJS and webpack helps to load your scripts by letting users see your layout before it gets functional. It has a great positive impact on conversions for first-time users; make sure to track the dependencies that have been loaded to avoid loading it twice. Even the library dependencies sum up a lot to loading times; so try to use them less and avoid entirely if possible. You can also rely on in-browser technology to reduce your dependency on external libraries.

Make use of document.getElementById() and ‘this’ (local scope)

You can use jQuery to create some specific selectors which are based on tag names and classes to necessitate several iterations as jQuery loops through DOM elements for searching a match. To speed this up, you can opt for this method:

// With jQuery
var button = jQuery('body div.window > div.minimize-button:nth-child(3)')[0];
// With document.getElementById()
var button = document.getElementById('window-minimize-button');

Also, ‘this’ allows boosting performance by reducing dependency on global variables or closures which are residing higher in the scope chain by writing asynchronous code with callbacks. You should avoid ‘with’ keyword as it modifies the scope chain and drags down the performance as given:

var Person = Object.create({
    init: function(name) {
        this.name = name;
    },
    do: function(callback) {
        callback.apply(this);
    }
});

var bob = new Person(‘bob’);

bob.do(function() {
alert(this.name); // ‘bob’ is alerted because ‘this’ was rewired
});

But, if you wish to load your scripts asynchronously and defer until the rest of the page gets finished loading, you can add async or defer attributes as given:

// load example.js without interrupting your webpage's rendering
<script src="example.js" async></script>
// load example.js after the page has finished loading
<script src="example.js" defer></script>

The graph depicts the difference between synchronous and asynchronous loading. The former one needs to wait for the previous asset to finish loading before pursuing a new one while the latter can load assets at the same time.

timeline

What are the tools to improve JavaScript performance?

There are several code compression tools that are designed to help the developers get optimized applications for a little extra support. With the help of code compression and code minification, it helps to remove unnecessary characters from source code that results in smaller files sizes and faster load times. Hers a list of tools you can choose from:

Google Closure Compiler

The most used tool for making JavaScript gets downloaded faster and run smoothly. Instead of compiling your source code language to machine code, it directly compiles to remove the dead code and rewrites what’s left out. On top of that, for analyzing, parsing, and rewriting your code for optimal performance, Google closure compiler also helps to double check your syntax and variable references.

Packer

It is the simplest tool to use as you just need to paste your code into the Packer ad hit ‘Pack’ button to condense your code in seconds. It also offers on the fly decompression to boost your app performance.

YUI Compressor

It is a command-line tool that is created by Yahoo to deliver a higher compression ratio than most of its competitors by compressing all CSS files. This can reduce up the loading time and increases your performance along with memory management.

Before you go…

We saw many individual tips to boost up your JavaScript performance and if they are implemented together, you can notice how a significant improvement is made on your website. It is difficult to remember all of the pointers hence, you can keep your own personalized list of Javascript optimization techniques to solve the problems. Keep Learning!

Author Bio: Barkha Patel is a Technical Content Strategist at Software Development Company – TatvaSoft.com. She likes to write about technology advancements regularly. Her work focuses on balancing information with techie needs–but never at the expense of providing an entertaining & Valuable read.

NO COMMENTS

Leave a Reply