Adapt.js is a lightweight (848 bytes minified) JavaScript file that determines which CSS file to load before the browser renders a page. If the browser tilts or resizes, Adapt.js simply checks its width, and serves only the CSS that is needed, when it is needed.

A potential drawback of Adapt.js is the possibility of a brief flash of unstyled content as a new stylesheet is being fetched (think of it as "Ajax" for CSS). I have done my best to mitigate this by keeping CSS files small (3 KB). It is worth noting this is a proposed, not prescribed, approach to a problem with multiple solutions.v

Configuration

// Edit to suit your needs.
var ADAPT_CONFIG = {
// Where is your CSS?
path: 'assets/css/',
// false = Only run once, when page first loads.
// true = Change on window resize and page tilt.
dynamic: true,
// Optional callback... myCallback(i, width)
callback: myCallback,
// First range entry is the minimum.
// Last range entry is the maximum.
// Separate ranges by "to" keyword.
range: [
'0px to 760px = mobile.css',
'760px to 980px = 720.css',
'980px to 1280px = 960.css',
'1280px to 1600px = 1200.css',
'1600px to 1920px = 1560.css',
'1940px to 2540px = 1920.css',
'2540px = 2520.css'
]
};

For all possible options ā€” Read moreAdapt.js, accepts a few parameters: path is where your stylesheets reside, dynamic is a boolean (true or false) that says whether to watch the window for its resize event, also triggered by tablet or phone tilt. Widths and optional CSS files are specified in range. The defaults are shown in the adjacent code example. You can also specify an optional callback function, that will pass range index and width.

Open Source

Just like the 960 Grid System itself, Adapt.js is licensed underGPL and MIT. That means it is free, as in speech. If you want to use it in a product that is already licensed under the GPL, you can. Or, if you want to use it in a commercial product, you can choose the MIT license instead. No strings attached. The code is available via GitHub.


Before you leave

I know, "another newsletter pitch" - but hear me out. Most JavaScript newsletters are terrible. When's the last time you actually looked forward to getting one? Even worse, when's the last time you actually read one rather than just skim it?

We wanted to change that, which is why we created Bytes. The goal was to create a JavaScript newsletter that was both educational and entertaining. 101,875 subscribers and an almost 50% weekly open rate later, it looks like we did it.

Delivered to 101,875 developers every Monday