Monday, December 12, 2011

Adaptative web design: loading resources dinamically

Adaptative web design (also known as responsive web design) is a tecnique that adapts web pages to the devices (desktops, tablets and phones).

This tecnique uses many differents technologies. In this blog post I don't want to explain every detail of this tecnique but it could be useful reading an in-depth tutorial:
http://webdesignerwall.com/tutorials/responsive-design-with-css3-media-queries

The remaining Issue
Using media queries to adapts a web page to mobile has a huge drawback.  We load to a mobile phone every bit of the web page and then we hide text and shrink full size images and video. The results is great, but the speed ? Is it possible to avoid downloading all this unused stuff ?

I think I found an elegant solution with these scripts https://github.com/sithmel/jQuery-decomment .
They are very simple (only 31 LOC) and are designed to work together. They are doWhenVisible and decomment.

An example:
Our Web page contains a very big and complex slideshow but in the mobile version of our web site we'll hide it using css (is very big and heavy to load).

HTML

<div class="bigslideshow">
<!--
    <img src="bigimage1.jpg" />
    <img src="bigimage2.jpg" />
    <img src="bigimage3.jpg" />
-->
</div>

CSS

@media screen and (max-width: 650px) {
    .bigslideshow{
       display: none;
    }
}

Javascript

$.doWhenVisible('.bigslideshow', function (){
    this.decomment(); // remove the comments
    this.jcarousel(); // initialize the slideshow
});

Very easy ! doWhenVisible execute a callback (only once) when a DOM element becomes visible (it checks every time the page is resized).
Decomment obviously removes comments. Removing comments is just like adding dinamically DOM nodes. The browser reacts downloading the resources and rendering the whole.

We can go even further using a script loader to load our js only if effectively used (we use require.js here):

$.doWhenVisible('.bigslideshow', function (){
    require(["jquery.jcarousel.js"], function() {
    //load jcarousel
        this.decomment(); // remove the comments
        this.jcarousel(); // initialize the slideshow
    });
});
Right now I'm very proud of these little scripts!