Learning Less.js
上QQ阅读APP看书,第一时间看更新

The dangers of using Less on the client side

So far, we've worked through how you can install Less in your code and use it to compile code into valid CSS, as each page is displayed.

Surely we should be good to start using Less, right? After all, we have the library in place, we know how to add it in, and know something of what to expect when styles have been compiled...or perhaps not. There is one critical point we've missed; let me explain.

When Less first came out, it was originally written using Ruby; this meant code had to be compiled first, before including the results in website pages, as valid CSS. Although this was a perfectly valid procedure, it made development slower, as extra steps were required in order to compile the Less code and include it in web pages.

The rebasing of the library in JavaScript led to a 30 to 40 percent increase in speed—this led to the temptation to include the library directly in code, along with the raw Less code. This worked well enough, while removing the need to compile the code separately.

This, however, is no longer deemed good practice, at least for production sites, for a number of reasons:

  • JavaScript can be turned off—a reliance on JavaScript to control the styling for a site means that it will break, resulting in a messy site!
  • A reliance on a JavaScript-based library means that another HTTP request has to be made to the server, which can result in increased loading times, particularly for script-heavy sites.
  • On a content-heavy site, with a lot of styles, this can lead to a noticeable increase in rendering times, as the styles have to be compiled dynamically before content is rendered on.
  • Most mobile platforms cannot handle the compilation of Less (nor the associated JavaScript file) dynamically and will just abort the execution, which will result in a mess.

This doesn't mean compiling on client side is a complete no-no, it should just be limited to working in development environments, or in instances where it is beneficial to store the library locally, such as within an HTML5 application.

You will note that many of the examples throughout this book will use Less client-side. This is to ensure that you, as the reader, are exposed to the whole experience; as we are working in a development/demonstration capacity, this is not an issue. When working on production sites, the Less code should always be precompiled first, before adding it to the site.