JavaScript is a truly amazing tool for front-end programming, creating interactive, feature-rich websites and fast, seamless web applications. Every front-end developer knows JavaScript, but when used without caution or expertise, it can be a double-edged sword. Poorly written JavaScript code can slow your website, negatively affecting load times and rendering speed. In this article, we’ll cover some useful tools to help you avoid the “dark side effects” of JavaScript.
1. ORDER IN WHICH ELEMENTS ARE LOADED
First, it’s important that all elements in the <head>
section are pre-loaded, before the visitor sees anything in browser, then all subsequent elements are ordered to load in a logical way. Any JavaScript inside the <head>
section can slow down a page’s rendering. Here’s a look at the difference between an optimized and an unoptimized page load:
During the load of unoptimized page, chances are a user will see a “white screen” before the full page is then loaded. An optimized page load (render actually) happens in a more step-by-step way, allowing a user to see some content gradually until page the page loads fully.
WHY IS THE LOAD ORDER IMPORTANT?
With a little research via Google, we can see how load order impacts user focus:
Google calls this the RAIL model.
2. MINIFY JAVASCRIPT CODE FOR SMALLER FILE SIZES.
Minifying code is different from obfuscating code, but both are methods of transforming JavaScript—to be more difficult to read, or to make it smaller. Minification accomplishes the latter, and can shrink file sizes to decrease page load times.
Line breaks, additional spaces, comments etc.—all of this increases the size of a JavaScript file and affects the speed of page load. Compressing the code solves this issue well. Machines are not sensitive to the visual style of code like a human would be. Computers can read and launch minified code, even if all of your Javascript fits in just one string.
3. OPTIMIZE IT!
Optimization is a special type of JavaScript minification. These kind of minimizers not only delete unuseful white spaces, commas, comments etc. but also help to avoid ‘dead code’:
- Google Closure Compiler
- UglifyJS
- Microsoft AJAX Minifier
- How does optimization work? Here’s an example:
Before optimization:
function test(node) { var parent = node.parentNode; if (0) { alert( "Hello from the other side" ); } else { alert( "We love Upwork" ); } return; alert( 1 ); }
After optimization:
function test(){alert("We love Upwork")}
What exactly did optimization accomplish?
- The variable parent will never need to be used, so it gets deleted;
- False if() {…} is deleted as ‘dead code’; true else leaves only one possibility.
- Return is deleted; it’s also dead code.
4. ASYNCHRONOUS LOADING OF JAVASCRIPT: DEFER AND ASYNC TAGS
Asynchronous loading of JavaScript is a type of sync loading. It means that your website loads in a multi-streamed way.
When the browser finds the string with <script src="some.js"></script>
, it will stop creation of DOM and CSSOM models while the JavaScript is executed. This is why most JavaScript code is located after the main HTML code.
To understand this point a little better, take a look at this code:
<html> <head> <script src="big.js"></script> </head> <body> This text will not be present until big.js is loaded. </body> </html>
Instead, you can add an async tag to the JavaScript so that creation of the DOM model happens in parallel, and won’t be interrupted while the JavaScript is loading and executed.
<html> <head> <script src="big.js" async></script> </head> <body> This text will be present and it’s not dependent with big.js loading progress. </body> </html>
Use caution if your JavaScript must make some manipulations to the HTML or CSS, or if you’re loading a script in a strong order (e.g., jQuery-dependent libraries).
For example, if you’re using the very popular bxSlider on your website and like CDN for jQuery, to add bxSlider you could add this 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" />
As you can see, jQuery is loading from the Google CDN but bxSlider is local. If we add async tag to the string, which includes jQuery, it may create errors with the bxSlider if jquery.bxslider.min.js is loaded before jquery.min.js. In this case, order is very important so another tag is needed: defer.
If the browser sees a defer tag with JavaScript code, it will not stop loading the DOM and CSSOM models. All scripts with a defer tag will be loaded and run immediately after the DOM and CSSOM models are completed. Any scripts will be loaded in the order you code.
<script src="1.js" defer></script> <script src="2.js" defer></script>
In this case, 2.js will not be loaded until 1.js is loaded, and so on.
Important! Defer and Async tags are available only for external scripts (with src=”” tag). If you will try to use them for internal scripts like <script>…</script> tags, defer and async will be ignored. |
5. EXCLUDE UNUSED COMPONENTS OF .JS LIBRARIES.
Most developers use libraries like jQuery UI or jQuery Mobile as is. This means that the code includes all possible components of each library, when you may only need two or three. A similar situation occurs with other JavaScript libraries as well. If you have the ability to manage what components will be included in your package of library, definitely do it. Your website will load much faster, and your visitors will get a better experience.
Visit the Download Builder of jQuery Mobile or jQuery UI to create your own package of those famous libraries.
6. USE THE HTTP/2 PROTOCOL.
This second, encrypted version of the main Internet protocol can provide you with a lot of cool features, including the asynchronous download of external files, most notably JavaScript. While HTTP requires deep learning and an advanced knowledge of JavaScript theory, HTTP/2 can make JavaScript load faster. Learn how to start using HTTP/2 in this article.
Use this website to get your own experience with HTTPS and HTTP/2. Another one test is Aka`mai HTTP/2 demo.
7. USE A JAVASCRIPT CONTENT DELIVERY NETWORK (CDN)
A CDN is not a panacea. For example, if your project is not worldwide and you opt to use a CDN that doesn’t have a local server in your country (e.g., the Russian Federation), this will increase a page load time. Using a CDN is supposed to make things run faster, but in certain cases, it can have the opposite effect.
You can use Cedexis to generate reports that compare various CDNs to help you to decide which provider is most affordable for your use case. Also, you can get more comparisons of CDNs here.
The above reports provide you with CDN comparison information, such as support for instant setup and different types of pricing. To get an idea of which CDN is best for your library, check out thousands of options at this site.
8. GZIP MODULE FOR APACHE, NGINX, AND NODE.JS
Gzip is an amazing technology created back when the internet wasn’t as high-speed as it is today. Archivators were a popular technology (they’ve since decreased in popularity since USB flash drives can give up to 1TB of storage). The idea was to use Archivators for Internet web traffic (similar to creating files of websites), so gzip was developed to deflate files on web servers, compressing static (textual) files down to 99% of their original size. Because javascript is a textual file, gzip can be used to compress JavaScript files and also help to decrease page load times. Check to see if your web server technology has support for gzip here:
There are modules for some of the most famous web servers, including Apache and Nginx.
Because JavaScript can be used not only for front-end development but back-end development as well (thanks to Node.js), you can compress JS files with the zlib module for Node.js.
It’s super fast and easy to set up:
const zlib = require('zlib');
Use it a few ways, like the following:
const gzip = zlib.createGzip(); const fs = require('fs'); const inp = fs.createReadStream('input.txt'); const out = fs.createWriteStream('input.txt.gz'); inp.pipe(gzip).pipe(out);
OPTIMIZATION TOOLS WHICH WORKS WITH GZIP
There’s a special type of JavaScript code optimization, variables inlining, that’s essentially related to gzip. Let’s look at an example below.
Before optimization:
(function() { var isVisible = true; var mes = "We love Upwork very much"; window.sayHi = function() { if (isVisible) { alert( mes ); alert( mes ); alert( mes ); alert( mes ); alert( mes ); alert( mes ); alert( mes ); alert( mes ); alert( mes ); alert( mes ); alert( mes ); alert( mes ); } } })();
After optimization:
(function() { window.sayHi = function() { alert( "We love Upwork very much" ); alert( "We love Upwork very much" ); alert( "We love Upwork very much" ); alert( "We love Upwork very much" ); alert( "We love Upwork very much" ); alert( "We love Upwork very much" ); alert( "We love Upwork very much" ); alert( "We love Upwork very much" ); alert( "We love Upwork very much" ); alert( "We love Upwork very much" ); alert( "We love Upwork very much" ); alert( "We love Upwork very much" ); }; } })();
Basically, you can see that the optimized code became longer because the variables mes were perlased with its value. What Gzip does is to find repeating elements and replace them with small ‘symbols’ from the archive dictionary so that the final code after optimization and gzip isn’t bulkier, despite optimization.
9. MOVE SOME THE CSS AND JAVASCRIPT CODE OF YOUR FIRST SCREEN TO THE TOP OF YOUR CODE FOR FASTER LOADING.
This technique helps your page load faster, but requires pretty good knowledge of DOM and SCCOM. The idea is to bring a minimum amount of CSS and JavaScript code to the <head>
section so loads it immediately, while the more extensive code is stored in separate .css and .js files, like usual.
10. WHERE YOU CAN, USE CSS3 EFFECTS IN PLACE OF JAVASCRIPT.
Older versions of CSS like 1.0 or 2.0 were not as powerful on their own and required a bit more JavaScript to create more advanced styling effects. But CSS 3.0 is a very capable language on its own, with lots of added functionality that requires less JavaScript. Another benefit is that CSS can be pre-compiled so CPU usage for CSS is lower than JavaScript.
For example, you can add sliders like CSSSlider in CSS3 and HTML5 without any JavaScript at all like. Here’s an another free one to try:
HTML:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>CSS Slider</title> </head> <body> <base href="https://s3-us-west-2.amazonaws.com/s.cdpn.io/4273/"> <div id="slider"> <figure> <img src="austin-fireworks.jpg" alt> <img src="taj-mahal_copy.jpg" alt> <img src="ibiza.jpg" alt> <img src="ankor-wat.jpg" alt> <img src="austin-fireworks.jpg" alt> </figure> </div> </body> </html>
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; }
Watch a demo here.
11. CACHE IT.
Caching is important, especially for JavaScript—not just JavaScript files, but framework functions, too.
Here’s a sample to try:
Code without cache:
function SieveOfEratosthenesUncached(n) { // define array of possible primes var primes = []; for (var i = 0; i < n; ++i) primes.push(true); // find possible primes for (var i = 2; i < Math.sqrt(n); i++) if (primes[i]) for (j = Math.pow(i, 2), k = 0; j < n; k++, j = (Math.pow(i, 2) + (i * k))) primes[j] = false; // prepare possible primes as return var results = []; for (var i = 2; i < primes.length; ++i) if (primes[i]) results.push(i); return results; }
Code with cache:
function SieveOfEratosthenesCached(n, cache) { var primes = cache; for (var i = cache.length; i < n; ++i) primes.push(true); // find possible primes // Improve speed by prevent active looping for (var i = 2, l = Math.sqrt(n); i < l; ++i) if (primes[i]) for (j = Math.pow(i, 2), k = 0; j < n; k++, j = (Math.pow(i, 2) + (i * k))) { primes[j] = false; } // prepare possible primes as return var results = []; for (var i = 2, l = primes.length; i < n && i < l ; ++i) if (primes[i]) results.push(i); return results; }
Results of running:
CONCLUSION
As you can see, there are numerous technologies and techniques to help you with optimization of JavaScript code to speed up download and rendering times. If you’re looking to speed up your page load times with any of these popular optimization techniques, browse Upwork to find a skilled freelance JavaScript developer for the task.