Adapt.js: More efficient responsive design

As the mobile space continues to grow, there has been a growing interest in Responsive Web Design, making use of CSS media queries to selectively target device screen size and layout orientation in CSS stylesheets. But as Jason Grigsby points out, media queries have substantial drawbacks. Since media queries only filter styles and (and related image assets) on the client, you may end up pushing a lot of data down to the client that the user may never see. In mobile applications, this is extremely costly.

Nathan Smith, JavaScript hacker and creator of the 960 Grid System has released Adapt.js, a lightweight JavaScript library that will let you specify a list of stylesheets and the screen sizes for which they should be loaded:

// Edit to suit your needs.
  // Where is your CSS?
  path: 'assets/css/',

  // false = Only run one time, when page first loads.
  // true = Change for window resize or page tilt too.
  dynamic: true,

  // First range entry is the minimum.
  // Last range entry is the maximum.
  // Should have at least one "to" range.
  range: [
    '760px            = mobile.css',
    '760px  to 960px  = 720.css',
    '960px  to 1280px = 960.css',
    '1280px to 1600px = 1200.css',
    '1600px to 1920px = 1560.css',
    '1920px           = fluid.css'

When your page loades, the appropriate layout is written to the <head> of your document based on the screen width of the page. If you enable the dynamic setting, additional stylesheets will be fetched when the user resizes the browser window or rotates their mobile device.

Silver bullet?

Nathan admits that every project is different and there are tradeoffs between stylesheet size and extra network hops:

As with any area in which technological approaches are open for debate, there is the danger of religious fanaticism, where we each rally behind a respective method and defend it vehemently. I would caution you to weigh the options, consider mobile users, and choose an approach makes sense for you.

[Source on GitHub] [Web site]

News Films

Our little film studio focuses on telling developer-centric stories that need to be seen.

Beyond Code: Season 3 / GopherCon 2015

0:00 / 0:00