How to Improve Website and Rendering Speed with JavaScript Code Optimization | Hacker Noon

Over 1.5 billion websites in the world are using JavaScript language. If a developer is not well-versed with the JavaScript language and the code written for the website is poor, it may slow down your website, negatively affecting load times, and rendering speed. Users generally get engaged and attracted towards high-performing JavaScript websites than low-performing sites. In this article, we are going to cover some useful tools which will help you enhance the speed of your JavaScript-enabled website.

image

sarrahpitaliya Hacker Noon profile picture

@sarrahpitaliyasarrahpitaliya

Avid reader and technology writer www.radixweb.com

Since its invention, JavaScript has truly ruled the world of developers for front-end programming. It has allowed front-end developers to develop interactive, fast, robust, user-centric, and feature-rich web applications. Therefore, it has turned out to be the most popular language in the software development industry.

A report states that over 1.5 billion websites in the world are using JavaScript language. However, the number of websites using this technology is around 95%. So, we can conclude that every computing device uses JavaScript, including iOS/macOS, Android, Windows, Linux, Smart TVs, etc.

“Software ate the world, the web ate software, and JavaScript ate the web.”

Every front-end developer is familiar with JavaScript. However, if it’s used without expertise or knowledge, it can be a double-edged sword. If a developer is not well-versed with the JavaScript language and the code written for the website is poor, it may slow down your website, negatively affecting load times, and rendering speed. 

When developing a modern application, it’s essential to analyze, monitor, and optimize its performance. However, you should be aware of how fast your website is. Performance plays an important factor in the success of any online venture.

So, now you must be wondering, why does speed matter for the success of the website?

Why Does Speed Matter?

Website speed or performance plays an important role in the success of your online business. Users generally get engaged and attracted towards high-performing JavaScript websites than low-performing sites.

“Performance has directly impacted the company’s bottom line.” – YouTube

Pinterest reduced perceived wait times by 40%, increasing search engine traffic and sign-ups by 15%.

COOK reduced average page load time by 850 milliseconds which increased conversions by 7%, decreased bounce rates by 7%, and increased pages per session by 10%.

As per the report, the poor performance of the website will negatively affect business goals. Therefore, as per this statement by BBC, they lost around 10% of users for every additional second their website took to load. Hence, it’s advisable to leverage comprehensive JavaScript development prowess to power up your business. 

Let’s understand the reasons in real-world stats why code optimization is important: 

  • Research by Google says that around 53% of visitors will leave your website if a webpage doesn’t load within three seconds. 
  • 47% of users expect a maximum of 2 seconds loading time for an average website. 

Here, in this article, we are going to cover some useful tools, which will help you enhance the speed of your JavaScript-enabled website and avoid the dark side effects.

If you don’t optimize your JavaScript code properly for your project, you may face the following problems: 

  • A considerable number of host interactions 
  • Lack of event handling 
  • Code shuffling 
  • Inefficient loops 

How to Load the JavaScript Faster

File compression, usage of asynchronous code & defer tags, and cache the browsers are preferred ways to load the JavaScript faster. 

How Can I Enhance the Performance of JavaScript?

Code optimization plays an important role in enhancing the performance of the JavaScript website. You can avoid memory leaks, delete the unused code, files, features, and use the compressed data for better performance. 

Furthermore, you can implement a CDN, minimize external requests, and focus on creating a clean code to increase the overall performance.

Will Minifying Help to Improve Performance?

The minifying method will help you remove the unused functions, comments, commas, etc. Eventually, it will improve the web performance. 

So, now without any further ado, let’s focus on tips to optimize JavaScript code for front-end developers. 

1) Remove Unused Features and Code

The more you write for a website, the longer it takes to load. Therefore, while developing a website, you must optimize the JavaScript code using JavaScript Code Optimizer. It will assist you in removing the unused functionalities, features, and code in the development environment. 

Google Clouser Compiler and Uglify JS are the finest JavaScript Code Optimization Tools. These tools remove commas, comments, and dead code.

Code Before Optimization

function test(modevar parent = node.parentNode; 
if(0) 
{ 
alert(“Hello. This is the code before optimization.”); 
} 
else 
{ 
alert (“Hello. Greetings for developers.”); 
} 
return; 
alert(1); 
}

Code After Optimization

function test() 

{
alert (“Hello. Greetings for developers.”); 
}

So, here, what did we do? 

  • We removed the variable parent as it will never be used again. 
  • Also, we removed False if() {…} as it’s a ‘dead code’. 
  • Return is deleted; it’s also dead code. 

2) Minify JavaScript Code

Minifying and obfuscating JavaScript code methods are used to transform the JavaScript. However, both these methods are different. Minification can reduce the size of files to decrease the page loading time.

Some factors like a line break, additional spaces, comments, and more increase the size of the JavaScript file and affect the page loading speed. With code compression, you can resolve this issue. Even though all of your JavaScript code fits in just one string, your machines can be able to read and launch minified code.

3) Work On Memory Leak Issue

As we know, without any doubt, Garbage collection is performed automatically in JavaScript, and you can’t ignore the memory section. So, as a front end developer, you have to use the function like WeakSet and WeakMap to solve the issue of memory leaks.

Therefore, you can use Chrome Dev Tools to avoid the memory leaks problem.

4) Avoid Irrelevant Iterations

A loop always consumes a significant amount of time to load the project, irrespective of its size. Hence, you should break the large cycle of a loop very soon. However, you can execute this process with two keywords: break and continue

For example, if you don’t use the break keyword; this loop will execute 100 times. 

let arr = new array(100); 
arr[36] = ‘found’; 
for (let i = 0; i < arr.length; i++) 
{ 
if(arr[i] === ‘found’); 
break; 
}

5) Asynchronous JavaScript Loading: Defer and Async Tags

JavaScript asynchronous loading is a part of sync loading. It signifies that your website is now prepared to load in a multi-streamed way.

image

When the browser encounters <script src=”some.js”></script>, the creation of DOM and CSSOM models will be stopped while JavaScript is executed. Therefore, many times, JavaScript code is written after the main HTML code.

Well, to clear your doubts, let’s view an example here:

<html>  
<head>  
<script src="big.js"> 
</script> 
</head>  
<body> This text will not be visible until big.js is loaded. </body>  
</html>

Now, in the JavaScript code, you can use the async tag to ensure that the DOM model is created parallelly and not stopped while the JavaScript is loaded or executed.

If your JavaScript needs to manipulate the HTML or CSS or load a script in a specific order (jQuery-dependent libraries), use caution.

Let’s view another example; if you are using a popular bxSlider and CDN for jQuery on your website, you could add the given code to your HTML. 

<!-- jQuery library (served from Google) -->  
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>  
<!-- bxSlider Javascript file -->  
<script src="/js/jquery.bxslider.min.js"></script>  
<!-- bxSlider CSS file -->  
<link href="/lib/jquery.bxslider.css" rel="stylesheet">

In the above code, we can see that bxSlider is local, whereas Google CDN loads jQuery. So, if we try to add an async tag to the string (including jQuery), errors may occur with the bxSlider if jQuery.bxslider.min.js is loaded before jQuery.min.js

Therefore, there’s in need of another tag – defer.

The DOM and CSSOM models will not be loaded, if the browser encounters a defer tag with JavaScript code. Once the DOM and CSSOM models are complete, every defer tag script will be run instantly. Any script will be executed in the order you code. 

<script src="1.js" defer></script> 
<script src="2.js" defer></script>

In the above case, 2.js will not be executed until 1.js is loaded. 

Here, defer and async tags are ready to execute only for external scripts (with src=”” tag). And these tags will be avoided, if you use them for internal scripts like <Script>…</Script> tags. 

6) Use HTTP/2 Protocol

One of the most advanced and latest versions of the HTTP protocol is HTTP/2. It offers you many features by improving the JavaScript code performance. This will lead to the enhanced website speed.

HTTP/2 handles multiple requests and responses all together. So, it helps to enhance the load time of JavaScript.

If you are in a dilemma, you can check the difference between these protocols: HTTP/2 vs HTTPS. Another test is Aka`mai HTTP/2 demo.

image

7) A Proper Order to Load Elements

Element organization during the loading process is an important tip for JavaScript code optimization. Here, every element in the <head> section is pre-loaded, so it appears on the user’s screen before they see anything on the web browser. Hence, it’s essential to manage order to display the result on the screen.

Here, the unorganized elements of the page always show a white page to the user. So, it’s important to organize all the elements in a proper and logical way. It will surely help to increase user engagement.

image

With the in-depth research, we have concluded that how to load order impacts user focus.

0 to 16 ms

A screen updates 60 times per second. This data show how much time will a single frame take to appear on the screen (1000/60=16). People are good at monitoring motion, and they will be frustrated if the expectation of motion is not met, whether through variable frame rates or periodic pauses. 

0 to 100 ms

If it responds to a user action within this time frame, they’ll think the result was immediate. 

Any link between action and reaction has been broken. 

100 to 300 ms

Users experience a slight but predictable delay. 

300 to 1000 ms

For most users, loading pages or switching views is a task. 

1000+ ms

Users lose focus on the task they are working on after 1000 milliseconds (1 second). 

10,000+ ms

The user is likely to become frustrated and abandon the task; they may or may not return later. 

Well, Google calls it a RAIL Model

8) Use a JavaScript CDN

With the help of a CDN, you can significantly improve the speed and performance of your website. When you use a CDN, you link your website’s static content to an extended network of services across the globe. Well, it’s very important if your website caters to an overseas audience.

A CDN loads your data from the nearest server and present to the visitors. With the help of a CDN, your files will automatically be compressed or optimized for rapid delivery for your visitors. This makes things run faster.

image

Well, you can compare various CDNs and see which one is best for you. 

9) Use CSS3 Effects in Place of JavaScript

When we compare CSS3 with its previous versions – 1.0 and 2.0, the older versions were less powerful and required extra JavaScript to achieve more advanced styling effects. However, CSS3 comes up with many functionalities that require less JavaScript. Furthermore, CSS can be pre-compiled, so it consumes less memory on CPS than JavaScript.

Let’s consider an example here.

Without any JavaScript, you can add CSSSlider in CSS3 and HTML5. 

Here’s one to try: 

HTML:

<!DOCTYPE html>
<html lang="en"></html>
<head></head>
<meta charset="UTF-8">
<title>CSS Slider</title>
<body></body>
<base href="https://s3-us-west-2.amazonaws.com/s.cdpn.io/4273/">
<div id="slider"></div>
<figure></figure>
<img src="apple.jpg" alt="">
<img src="strawberry.jpg" alt="">
<img src="cherry.jpg" alt="">
<img src="pineapple.jpg" alt="">
<img src="kiwi.jpg" alt="">

CSS:

@keyframes slidy  
{  
0% { left: 0%; }  
20% { left: 0%; }  
25% { left: -100%; }  
45% { left: -100%; }  
50% { left: -200%; }  
70% { left: -200%; }  
75% { left: -300%; }  
95% { left: -300%; }  
100% { left: -400%; }  
} 
body { margin: 0; }  
div#slider { overflow: hidden; }  
div#slider figure img { width: 20%; float: left; }  
div#slider figure  
{  
position: relative;  
width: 500%;  
margin: 0; left: 0 text-align: left;  
font-size: 0; animation: 30s slidy infinite; 
}

10) Code Testing

Code testing is an important factor in analyzing performance issues such as memory leaks and patching them. 

Well, you can implement the given JavaScript testing tools to enhance the JavaScript performance.

Console.time()

Console.time() is used to track the time of operation execution.

Initially, you have to call simply:

console.time(label);

Here, “label” can be a unique name for your timer. At the end of the process, you can call:

console.timeEnd(label);

Here, operation time will be monitored from initial to end.

YSlow

YSlow is an open-source performance tool. It analyzes your website performance and gives optimization tips. Your website will be called by this tool and compared its performance adhering to Yahoo’s standards for high-performance websites.

This tool will execute your website and compare its performance against the standards of Yahoo for high-performance websites. However, it will give you a score between 0% and 100%.

JSFiddle.net

JSFiddle.net is a web development coding environment that executes in your web browser.

It supports:

  • JavaScript, HTML, CSS, and CoffeeScript
  • Boilerplates for React, Vue, and jQuery
  • The ability to demo code snippets and share them for code collaboration
  • Simple bug-reporting for GitHub issues

Wrapping Up

While developing a JavaScript application, it’s essential to balance between code readability and optimization. As we know, our code could be interrupted by machines, but it’s our responsibility to maintain it for better performance.

So, as a front-end developer, this article will help you optimize JavaScript code and enhance website speed. However, it’s not easy to implement or remember all of the given points for your JavaScript application. So, you should keep the list of tips to optimize the JavaScript code or save this article for your future reference.

I hope this article’s tips and information help you to develop a high-performance JavaScript website.

Tags

Join Hacker Noon