At Agira, Technology Simplified, Innovation Delivered, and Empowering Business is what we are passionate about. We always strive to build solutions that boost your productivity.

, ,

12 Extremely Useful JavaScript Hacks To Improve Performance

  • By Annamalai
  • January 23, 2019
  • 2474 Views

Gone are days, when the sites are produced with Static information’s & JavaScript has Completely dragged down all these sites by providing versatile dynamic practices. Food & beverages, Event management, Custom Listings, SAAS Tools, Learning management tools are the trends now! Fortunately, Our experts have succeeded & gained enormous experience in sorting out the best hacks to make more soft corner for the development aspects. Right from the JavaScript introduced, we have been indulging in various phase of JS practices to bring out the best for every product we deliver, So, this article is aimed to deliver some of the best tried, proven JavaScript Hacks & tips that are shared by our JS & MEAN-STACK experts.
Check our latest portfolio section to encounter more trending apps!
Let’s encounter the JS hacks now!

1. Combine Javascript Modules & Minify JS Files

Bundling application’s components into separate javascript *.js files and passing them through a JavaScript minification program will make the code leaner. It will make the coding to be standardized format and gives more readability for the developers and as well as to the application.

  • Sometimes, minified version of code is difficult to read and understand it’s the operation in detail, but it will definitely make the coding leaner & optimized.
  • Also, a minified source can shrink file sizes so it will directly help to reduce the page load times and will remove Line breaks, additional spaces, comments etc. 
  • Optimization is another type of JavaScript minification, which not only delete unnecessary white spaces, commas, comments etc. but also help to remove unused code blocks. Some of the famous tools/library to obtain code minification are as follows :

                  Google Closure Compiler
                  UglifyJS
                  Microsoft AJAX Minifier
All of this increases the size of a JavaScript file and affects the speed of page load. Compressing/ Minifying code will resolve these kinds of issue.

2. Use Scope (‘this’) In JavaScript

Using scope named ‘this’ will allow us to write asynchronous code with callbacks and also helps to boost application performance by reducing dependency on global variables and closures. Conversely, we should avoid the ‘with’ keyword because it modifies the scope chain, which will drag down the app performance. 

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
});

3. Asynchronous Loading Of External JS files

Asynchronous loading of JavaScript is a type of sync loading. It means that your website loads in a multiple-streamed way. When the browser finds the string with <script src=”some.js”></script>, it will stop creating DOM and CSSOM models so the JavaScript files will be executed. This is why most JavaScript code is located after the main HTML code.
To avoid this delay, we can add an async tag to the JavaScript script tag, so that creation of the DOM model will parallelly happen, and it won’t interrupt JavaScript files from loading or from execution. If the browser notices a defer tag in JavaScript code, it will not stop loading the DOM or CSSOM models.
All scripts with a defer tag will be loaded immediately and it will run after the DOM and CSSOM once all the loading  process got completed.  As the result, these scripts will also be loaded in the same order as like we coded.
Follow this incase if you want to load the script tags asynchronously,

<script src="operations.js" async></script>
//load operations.js without interrupting your webpage's rendering

And similarly follow this code if you want to use Defer tags, 

<script src="example.js" defer></script>
//load example.js after the page has finished loading

4. Remove Unused component From JavaScript Libraries

While using libraries like jQuery UI or jQuery Mobile, avoid using all possible components of them, when we need only a few functionalities of it. Most of the libraries, while downloading have options to manage what components will be included. It will also make the websites to load much faster, and increases better experience.

5. Use HTTP/2

HTTP/2 is the latest version of the HTTP protocol and provides great enhancements to improve JavaScript performance and  helps to speed up the site performance. HTTP/2 uses multiplexing, therefore it will allow multiple requests and responses to be sent at the same time. Moving to HTTPS itself will greatly help us to leverage all the features of HTTP/2 including performance.

6. Use Javascript Content Delivery Network (Cdn) For dynamic & Faster Loading

A CDN works by fetching static assets from the site’s server and caching them on their servers. When a browser makes a request, the static contents are served via the CDN rather than the site. It is way faster than usual because the CDN servers are globally distributed which will serve as proxies to determine which server is located nearer to the visitor.

  • CDN will load and distribute the files across the users based on their region
  • Save bandwidth
  • Boost performance
  • Reduce existing hosting costs and it’s mostly available without cost.
  • When a specific request is made, the server closest node of that user is dynamically determined. This optimizes the speed based on the content that is needed to be delivered to that user.

Also, when we use Google CDN will help in caching when the references frequently called within our application, This avoids multiple file downloads and increases cached file usage. If we are using local references it will download the files for every reference.

7. Compress and Decompress The Files In JS

JavaScript files can be very large. By using any of the zip applications like gzip, to compress the JavaScript & CSS files. It will save bandwidth, reduce time lag and latency, and improve the overall performance of the application. Most servers and clients today support gzip. When a gzip compatible browser requests a resource, the server will compress the response before sending it to the browser.

ALSO READ: 3 Must Known Features Of JavaScript ECMAScript 6 (ES6)

8. Use CSS3 in JAVASCRIPT

Most basic animations can be created with either CSS or JavaScript, but the amount of effort and time differs. Each has its pros and cons, but these are good guidelines to follow:

  • Use CSS,  when smaller, self-contained states for UI elements.
  • Use JavaScript when you need significant control over your web-animations. It will help us to stop, pause, slow down, or reverse.
  • Use requestAnimationFrame directly when you want to produce the desired effect, an entire scene by hand. It will be useful if we are building a game or drawing to an HTML canvas.

CSS-based animations and Web Animations are natively supported and typically handled by “compositor thread”. It’s totally different from the browser’s “main thread”, where styling, layout, painting, and JavaScript are executed. Because when the browser is running some imperial tasks on the main thread, this compositor thread can keep doing animations without being interrupted.

9. Caching DOM Object

In Scripting, it’s regular to have a script that repeatedly accesses certain DOM objects. For example, notice how the browser must dynamically look up the object, “document.images” two times for each loop.

  • To get document.images
  • And to change the images src.

If we have 10 images then this amounts to 20 calls, i.e., (n*2) calls to DOM images object.

<script type”text/javascript”>
for (var i = 0; i <document.images.length; i++) {
document.images[i].src=”image.gif”;
}
</script>

We can solve this issue by referring to the repeatedly accessed object in a user-defined variable, and instead of using subsequent references to the object we can use that variable. It will improve application performance and reduces the browser loading time as well. Now, you can notice in below code that the call of document.images has literally reduced to half of it.
Here is the alternative method is to “cache DOM object”.

<script type=”text/javascript”>
Var domImages = document.images;
For (var i=0; i<domImages.length’ i++)
domImages[i].src = “image.gif”;
</script>

10. Merging Arrays In JavaScript To Reduce Memory Consumption

If your requirement is of merging two small arrays, use Array.concat() function

var array1 = [“hai”, “welcome”];  
var array2 = [“good”, “morning”];  
console.log(array1.concat(array2));
// [“hai”, “welcome”,“good”, “morning”];

In Case of large arrays use, Array.push.apply(arr1, arr2)
The reason is, usually, the use of Array.concat() function on large arrays will consume a lot of memory, so to overcome that, we can use Array.push.apply(arr1, arr2) which will reduce the memory usage and also will take care of merging the second array with the first one.
Example:

var array1 = [“hai”, “welcome”];  
var array2 = [“good”, “morning”];  
console.log(array1.push.apply(array1,array2));
//[“hai”, “welcome”,“good”, “morning”];

It will also optimize the performance of your Javascript code irrespective of the size of an array.

ALSO READ: Leveraging The Power Of Javascript Console In Development

11. Avoid Keeping Unused JavaScript Variable

If your javascript document has accessed nodes or other objects from another document, avoid retaining those references once the script has finished using them. Delete or make the object null, once it’s not needed. This will increase memory usage.

var remoteDocument = parent.frames['sideframe'].document;
var remoteContainer = remoteDocument.getElementById('content');
var newPara = remoteDocument.createElement('p');
newPara.appendChild(remoteDocument.createTextNode('new content'));
remoteContainer.appendChild(newPara);
// Remove references
remoteDoc = null;
remoteContainer = null;
newPara = null;

12. Avoid Interacting with host objects DOM at the maximum

Each and every interaction with the host object in the user’s browser increases unpredictability and it results in performance lag. This problem often will raise within the application as a slow rendering of DOM objects. Actually, we can’t avoid such kind of interactions, but we can keep them to a minimum, to avoid such issues, wherever possible.
That’s all guys! Let us know your favourite hacks in the comments section.
Want to learn more? Trying to be a smart coder? curious to learn more tactics from the group of full-stack experts! Subscribe us below to post you our top engaging blogs & tips.

Looking for a Tech partner to dominate the digital world?

Annamalai

Tech lead at Agira, Around 10+ years of experience in IT industry; He demonstrated numerous success in various projects by directing the team with great guidance to apply the intense logics to accomplish the goal on time. Reliable working experience in modern web technologies, especially in Node.js and always loves to reserve his time in reading magazines & travelling.