Print Shortlink

Managing CSS files using Require JS – II

In the earlier post we created a file (index.html) that uses a stylesheet dev.css. dev.css internally refers to two other CSS files style1.css and style2.css. Loading index.html file sends three individual requests to the server one for each of the CSS file. In this post let’s discuss how we can optimize the loading of CSS files using Require JS.

In one of the articles on Require JS, we had discussed using the optimizer r.js with Node JS. We’ll use r.js in this example to optimize the CSS files. The folder structure of this example is shown below.

Let’s open command prompt navigate to the resources folder and run r.js using node as shown below.

node ..r.js -o cssIn=dev.css out=prod.css baseUrl=.

Running r.js will generate prod.css file that will have the contents of all the CSS files merged into one. You can include prod.css in index.html instead of dev.css. Running index.html file in chrome will now effectively send only one request to load the CSS contents, as shown below.

A neat and simple way to optimize loading CSS files.

Leave a Reply

+ 8 = twelve