Learn how to ship impactful customer journeys with Builder

Announcing Visual Copilot - Figma to production in half the time

Builder.io logo
Contact Sales
Platform
Developers
Contact Sales

Blog

Home

Resources

Blog

Forum

Github

Login

Signup

×

Visual CMS

Drag-and-drop visual editor and headless CMS for any tech stack

Theme Studio for Shopify

Build and optimize your Shopify-hosted storefront, no coding required

Resources

Blog

Get StartedLogin

‹ Back to blog

Web Development

The Ultimate Guide to Optimizing JavaScript for Quick Page Loads

April 12, 2022

Written By Steve Sewell

Techniques to speed up your website for greater conversions

Out of these two options, which one do you think people talk about more? 

  • A website loads fast, time to interactive (TTI) is low, and the user completes their tasks on the site without hassle. 
  • A website takes forever to load, the user has forgotten why they went on the site, and they vow to never go back there again.

The second one makes for a potentially more interesting story — but it’s also an incredibly frustrating user experience. The user is not only going to avoid going back to that site if they could, but they’re also going to warn their friends about it. 

As website developers, your biggest challenge is ensuring that your website displays all the information it needs to show your users right away. Optimizing images is one way to improve page load speed, but that alone is not enough. You also have to dig into your code and optimize your JavaScript. In this guide, we show you how.


Why you should optimize your JavaScript

Look at it this way: A blank website that has no elements added to it or no code is, by default, the fastest, with a 100/100 performance score. But a lot of us don’t want a barebones website. We want to create sophisticated, non-trivial websites and rich interactive experiences for our users. All these added assets take a toll on your users’ resources, from CPU and GPU to memory and network.

As you start adding elements to your site, however, you’re going to see an impact on the performance. Every third-party script, from your A/B testing to analytics to widgets, plus your own first-party code, is going to have a performance cost. (If we’d used the chatbot widget on the Builder.io website exactly in its default state, we’d have lost 50 performance points!) 

One takeaway from this is that the leaner and lighter your code is, the faster it will run. But the more unoptimized JavaScript you add, the lower the performance will go. This means heavy, sluggish web pages that take more than 14 seconds to get to interactive. And here’s why this matters: Research shows that 10 seconds is about the limit for keeping the user’s attention


The cost of unoptimized JavaScript 

We put several top websites into our Performance Insights tool (it’s free to try!), and overwhelmingly, optimizing JavaScript yielded a performance score boost of more than 50 points. JavaScript is the biggest culprit behind slow websites, and optimizing JavaScript is bound to have the most impact on speeding up your site.

Here’s what you stand to lose if your code is not optimized for faster page loads. 

User experience. JavaScript optimization is one step you absolutely cannot skip if you want to ensure a positive user experience. A slow website leads to a poor experience, which makes the user leave. If you want the user to stay on your website for longer, your page should load in under 3 seconds, according to Google. If your page load time increases from 1 second to 3 seconds, there’s a 32% probability of the user bouncing.

Conversions. Poor site performance has a direct impact on conversions. Especially with users accessing websites on their mobile devices, there’s never been a time when improving your site’s performance was more critical. For every one second delay in a page’s load time, there’s a 20% drop in conversions.

This becomes even more crucial for retail and e-commerce websites, where the user’s experience on the site leads to greater time spent, which might even lead to purchases and more money spent. In other words, optimizing your website to load faster has a direct effect on revenue. Deloitte says that just a 0.1 second site speed improvement led to 8% more conversions and 9% increase in average order value in retail.

SEO. There are many factors that affect SEO, and site performance is one of the key players. Your site’s performance influences its ranking in search results and thereby, the amount of organic traffic it gets. 51% of organic traffic to your website comes from online searches. And what’s more, on average, over 40% of revenue comes from organic searches, and 91.5% of searchers end up on one of the first-page results. 


How to optimize JavaScript

A fully optimized website will load fast and function well, regardless of the device, network quality, or browser capabilities. Here are a few widely accepted best practices.

Reducing the JavaScript in your code

When you send too many bytes of JavaScript, your page takes longer to load — and this becomes worse when your user’s network is slower. 

To minimize these network-related performance costs, developers can 

  • Only send the code the user needs through code-splitting to separate what’s critical and what’s not, and lazy loading components that are not render-critical.
  • Minifying the JavaScript
  • Compressing the JavaScript using gzip
  • Removing unused code
  • HTTP caching, Service Worker caching, and long-term caching to reduce network trips

This also involves deferring the load of elements that are not necessary for the initial page load. For example, above-the-fold components can be loaded first, and below-the-fold components can be deprioritized until the user scrolls. Having the right load order is critical to minimize the number of operations and has a direct impact on user focus.


Decreasing the costs of parsing/compiling and execution of JavaScript

As Tom Dale puts it, JavaScript is more expensive for the browser to process than the equivalently sized image or Web Font. While processing large, unoptimized images still comes with a lot of associated costs, it doesn’t get in the way of the main thread or prevent interfaces from getting interactive. JavaScript, however, can negatively impact a page’s interactivity.

Like I said before, the average web page takes 14 seconds to get to interactive. 4 seconds of that go into simply parsing and compiling JavaScript, which considerably delays your user’s ability to interact with your site. Not all your users have great network speeds and fast, high-end mobile devices. And users who have a great network connection might not have a fast phone, and vice versa. An average phone takes 2-5 times longer than the fastest phone in the market to parse and compile code. Fetching and processing JavaScript and other resources also takes time, which means that users can be left waiting a while before the page becomes interactive. 

To address these costs, it’s crucial to remove any non-critical JavaScript from your pages. This can help reduce transmission times, CPU-intensive parsing/compiling, and potential memory overhead. This also helps your page get to interactive quicker. Another great solution is using web workers. Web workers allow you to perform processor-intensive tasks in a background thread, so your main thread remains unblocked.

After the parsing/compiling of the code, it’s time for execution. This happens in the main thread, and adds some more precious time before your user can interact with the site. With the main thread blocked, the site remains unresponsive the entire time it takes to download, parse/compile, and run the code. One way to reduce this time is to split the code into smaller chunks for faster execution. Another recommended practice is inlining JavaScript in HTML, which significantly speeds up the page load. However, too much JavaScript can make the HTML files much too large. 


Why you should consider automated solutions to optimize JavaScript

There are several more traditional best practices than the ones explored above. When you optimize code, you have to ensure that only the critical and highly impactful parts are optimized to avoid wasting time and resources on optimizing non-critical components. This can be measured through the impact on the overall performance. Doing this manually is complex and time-consuming.

Not only that, optimized JavaScript makes the code more complex and significantly reduces readability. In other words, it’s more difficult to go through, maintain, and debug optimized code. The biggest challenge is maintaining the delicate balance between readability and optimization.

But even with these drawbacks, it’s still critical to optimize JavaScript. This is where newer automated solutions make all the difference. 


Optimizing first-party JavaScript for maximized performance

Writing good, clean JavaScript code using smaller functions and reusable code is, ultimately, the most effective solution, but it’s easier said than done. Plus, some JavaScript frameworks like React can be expensive in terms of performance.

The best way to reduce these performance costs is to remove as much JavaScript as possible from your code. 


Solutions

In ascending order of impact, these solutions reduce JavaScript in your code.

⭐️ Effective: Astro

Astro is a free, open-source static site builder that lets you compose your site using UI components from your favorite JavaScript web framework (React, Svelte, Vue, etc). Astro renders your entire site to static HTML during the build, resulting in a fully static website with all JavaScript removed from the final page. When a component does need some client-side JavaScript (e.g., image carousels), Astro only loads that one component (and any dependencies), leaving the rest of the site as static, lightweight HTML. While Astro is simple and easy to migrate to, it’s not the best solution for more complex apps.

⭐️ ⭐️ More effective: Marko 

Marko is a UI library that uses advanced compilation techniques to reduce the amount of JavaScript you need to load on your site. It’s a declarative, HTML-based language with progressive rendering, partial hydration, an optimizing compiler, and reduced execution time. It allows you to write code once that’s optimized for both the server and browser. While it’s more effective than Astro, it doesn’t completely eliminate JavaScript from your code.

⭐️ ⭐️ ⭐️ Most effective: Qwik

Qwik removes all JavaScript from the first page load, to be lazy loaded only as needed. Very similar to other web frameworks on a high level, Qwik renders a tree of components resulting in an interactive application. Qwik’s goal is to only download and execute the bare minimum of the application. Its main strategies include delaying execution and download of Javascript for as long as possible and serializing the execution state of the application and the framework on the server and resume it on the client. It’s open-source and maintained by Builder.


Eliminating performance issues from third-party scripts

Third-party scripts like pixel trackers, A/B testing, ads, widgets, CDNs, etc., are the biggest contributors to slow page load times. Third-party scripts, which are code that is embedded within your site, compete with your own code for the browser’s main thread, which delays content rendering. 

According to Google Web Fundamentals, third-party scripts can cause several issues including:

  • Too many network requests to multiple servers 
  • Sending too much JavaScript 
  • Resource-intensive script parsing and execution 
  • Insufficient HTTP caching
  • Lack of sufficient server compression of resources
  • Blocking content display until they complete processing
  • Use of legacy APIs (e.g document.write()) known to be harmful to the user experience
  • Excessive DOM elements or expensive CSS selectors

This becomes especially critical for e-commerce sites and online marketplaces that need these third-party scripts to run their business.


Solution: Partytown

Partytown is a lightweight open-source solution that reduces execution delays due to third-party JavaScript by offloading third-party scripts to web workers, which run in background threads. This frees up the browser’s main thread to run your own code. It’s maintained by Builder.io and is currently in beta. 


Simplifying JavaScript optimization for both developers and non-developers

You can cover plenty of ground with solutions like Qwik and Partytown alone. However, solutions like Partytown work best with backend scripts and are not built for render-critical scripts like personalization, A/B testing, building pop-ups and landing pages, etc., while still keeping JavaScript to a minimum. Some render-critical scripts, when done poorly, are known to break JavaScript frameworks and become difficult to debug. These scripts need to be served from the CDN immediately. However, layering all these JavaScript-heavy tools plugged directly into the browser leads to sluggish site speeds and the user waiting for plenty of things to load before they can see and interact with the site.

With API-driven development-intensive solutions, there’s always the pressure of developer dependency. Imagine an endless months-long backlog, with every single update to the site requiring developers to hard code. This can be extremely time-consuming and frustrating for both developers as well as non-developers who want to be able to make changes to the website with just a few clicks.

Composable, API-driven tools like Builder.io automate the coding using best practices. Builder makes high standards for performance, JavaScript optimization, etc., the default, while still retaining its simplicity and ease of use that serves both developers and non-developers well. Builder also aggressively splits code and ensures when loading a page or component that only the absolute needed Javascript is included. Builder serves minified, gzipped, and deduped Javascript, and similar to some other solutions listed above, can deliver content as very lightweight HTML and lazily load any additional JavaScript for interactive elements which are hydrated after initial load.


Conclusion

Optimizing JavaScript is central to maintaining fast page load times, providing a stellar user experience, increasing conversations, and boosting SEO. There are several traditional, tried-and-tested solutions that help developers optimize their code, but newer automated solutions can do the heavy-lifting, saving you time and resources to focus on more important work. To get started with optimizing JavaScript, improving performance, and enhancing user experience on your website, try plugging your site into our Performance Insights tool. 

Introducing Visual Copilot: convert Figma designs to high quality code in a single click.

Try Visual Copilot

Share

Twitter
LinkedIn
Facebook
Hand written text that says "A drag and drop headless CMS?"

Introducing Visual Copilot:

A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot
Newsletter

Like our content?

Join Our Newsletter

Continue Reading
AI8 MIN
How to Build Reliable AI Tools
November 15, 2024
Web Design11 MIN
Design Smarter with Figma Auto Layout
November 13, 2024
Web Development10 MIN
A Guide to Server-Side Rendering
November 12, 2024