Introduction

Website contains many JavaScript and CSS files, which must all be fetched from the server in order to fully load the web page. This process of downloading each file separately, takes more time as additional requests must be made which consequently increases latency.

Combine JS and CSS

Why Combine JavaScript and CSS

Combining your external Javascript and CSS files is beneficial for a few reasons.

  1. First, the number of requests can be drastically reduced given your website uses multiple CSS and JS files to render the page. If for example, your page loads 5 external CSS files and 5 external JS files, combining your Javascript and CSS into a single separate file each would result in 8 less requests.
  2. Second, all CSS files are render blocking which means that the more CSS files are loaded, the more likely this will interrupt your page’s critical path.
  3. Third, having multiple Javascript files can also be troublesome to the parsing of your HTML document given they are not deferred properly.

How to Combine JavaScript and CSS

The method used for combining external Javascript and CSS is basically the same for both file types. However there are a couple of things to consider for each of them:

Combine JavaScript

When combining Javascript, it is recommended to combine your existing files into 2 main files.

  • One file should contain the Javascript needed in order to render the page;
  • The other file should contain all other non-critical JS which in turn should be deferred.

This will allow you to load the web page much more quickly as the browser does not have to download and execute non-critical JS while it is trying to load above-the-fold content.

Combine CSS

To combine external CSS files, you can simply copy / paste all of your CSS code into one main file. Therefore all of the content from within the other CSS files will now reside within the main file allowing the browser to only make one request for a CSS file instead of multiple.

In addition, avoid using @import to import all of your external CSS files into one main file. This method can introduce additional delays since it is unable to download multiple stylesheets in parallel. Instead use the method described above which physically combines the CSS from one file into another, instead of just importing multiple files into one.

Other Optimize JavaScript and CSS

Combining external Javascript and CSS is one recommendation for helping to improve overall page performance by optimizing these two file types. However, for additional suggestions: