Responsive Media in HTML5 Sample Chapter
Responsive Media in HTML5 Sample Chapter
D i s t i l l e d
E x p e r i e n c e
$ 24.99 US
15.99 UK
"Community
Experience
Distilled"
C o m m u n i t y
Alex Libby
Responsive Media
in HTML5
Alex Libby
Chapter 3, Mixing Content, helps us bring it all together with a look at some of the
considerations or pitfalls of mixing responsive content and how we can reduce delays by
using preloaders to control when content is loaded and rendered on screen. We'll work
through an example of mixing both responsive images and video on the same page, so we
can see how it works in practice and consider what allowances may need to be made for
different platforms.
Chapter 4, Testing Responsive Media, delves into the world of testing our creations to
ensure they work properly. We'll see that there is no need for complicated tools as most
of our work can be done in a browser; we will also cover some tips to troubleshoot slow
performance issues and how we can make quick and easy changes to help improve speed.
Chapter 5, Using Frameworks, finishes up the book with a look at three real-world
examples of using responsive media in popular frameworks; our examples include a look
at WordPress, Less CSS, and Bootstrap. We'll take a look at some of the tips and tricks
(and plugins) available for use in WordPress, adding responsive media to a Bootstrapenabled webpage, and how we can use Less CSS to help better manage our CSS styles.
Mixing Content
Load Times For 69% Of Responsive Design Mobile Sites Deemed "Unacceptable"
A staggering fact, but absolutely true: a survey carried out by the mobile developer
company Tribilis in April 2014 found that for 155 sites surveyed, only 21 percent
loaded in four seconds or less on smartphones. Moreover, those that took longer
had an average page weight of 1.7 MB.
Sobering thoughts, but ones that perfectly illustrate the pitfalls of mixing videos
and images on pages in responsive design! We need to strike a balance between
displaying the right media content that is not too large or too small while keeping
our page load times small. This chapter works through some examples and details
some of the pitfalls associated with mixing content, which can lead to heavy pages
and long download times.
We'll cover a number of topics in this chapter, which will include:
Mixing Content
The banner image at the top of the browser window is too large. While this
may be okay on a desktop, it will choke smartphones; it needs to be resized.
The embedded video isn't respecting the boundaries of its container, with
the result that it is spilling out over the whole page, making the text difficult
to view.
We can improve on the use of the banner. Once we've changed it to a thinner
design, we can then add a media query to switch in a smaller version of this
thinner design.
Fortunately, these are easy fixes to make. Let's see what is involved:
1. Save a copy of mix-responsive.html and mix-responsive.css as
mix-responsiveV2.html and mix-responsiveV2.css respectively (in the
same folder). Don't forget to change the link to the CSS file from within our
HTML markup to point to the new file!
2. Look for the banner div on or around line 28 and remove the <img> tags,
so the HTML markup is as shown in the following line of code:
<div id="banner"></div>
3. Further down, look for <video controls> on or around line 34; we need to
encompass it within a wrapper <div>:
<div id="video-wrapper">
<video controls>
<source src="video/bigbuckbunny-480px.mp4" type="video/mp4">
<source src="video/bigbuckbunny-480px.webm" type="video/webm">
</video>
</div>
[ 60 ]
Chapter 3
5. Save the files. If we preview the results of our work in a browser, we can see
a significant improvement in the appearance of our page.
[ 61 ]
Mixing Content
Try resizing the page now; you should see that the video and image elements will
resize perfectly, without any spillage. In a nutshell, our changes have been very
simple. We've added a container to the video to which we've added the max-width
style attribute and set this to 100%. We then switched out the bulky banner to a
thinner version, setting this to retain the full width of its container when resized.
It is switched to a smaller version once we go below a screen width of 30rem.
There is a completed version of our demo with the fixes
in place. In the code download, look for and extract
mix-responsiveV2-finished.html and mixresponsiveV2-finished.css. Save both to the
same places as the original files to view the results.
Before we move on and take a look at how we can make allowances for mobile
devices when mixing content, I want to cover off a couple of tips that might help
give you a little inspiration:
We've embedded the video directly in the page. It works perfectly well,
but if we wanted to give it a little extra sparkle, we could consider using an
overlay. There are plenty available, but one good (responsive) example is
FrescoJS, available at http://www.frescojs.com/.
If you need to add responsive code for third-party embedded videos (such
as YouTube), you can use the service at http://embedresponsively.com/;
simply enter the URL of any video or image to embed and click on Embed
to get the code.
Okay! On we go! We've talked a lot about mixing content, but as we've seen from the
demo, there are some aspects where there is room for improvement. The alterations
we've made in our demo are just some of the pointers we can use to remove some of
the pitfalls of mixing content, so let's take a look at a few in more detail.
[ 62 ]
Chapter 3
2014
2015
2016
2017
94.0
94.0
95.0
96.0
Asia Pacific
87.4
90.0
92.6
93.9
72.4
80.6
86.6
91.7
North America
64.3
69.8
74.4
79.2
Western Europe
67.8
78.2
85.0
90.6
Latin America
58.5
65.0
70.1
75.2
Worldwide
79.1
83.6
87.3
90.1
The figures in the preceding table are percentage values taken from eMarketeer in
December 2013.
So that we don't fall into the trap of producing a responsive site that offers a poor
experience, let's take a look at some of the pitfalls we need to consider when mixing
media sources in responsive design:
The size and number of images on a page will directly affect how quickly
your visitors can view the page. To reduce the impact, we can use several
techniques:
[ 63 ]
Mixing Content
We need to be aware of the breakpoints in our design and alter our media
queries to suit. What may have worked well for images may not work
equally as well for videos, particularly if they are of different sizes.
Scaling smaller images to a larger size will result in the loss of quality; it is
recommended to start with large size images and dynamically resize them for
smaller devices. Once we get to a particular breakpoint, then we can switch
to using a smaller image by default to avoid images becoming illegible if they
have not been sized for a particular breakpoint / viewport width.
Scaling images can cause issues when they are reduced to a very small size.
The dimensions are likely to mean that we can't view the image properly, its
meaning will be lost, the file size won't be any smaller, and it may be better to
simply not display it instead.
If your site uses video, then one pitfall that can trip you up is the format
used. Although we only need to encode for MP4 or WebM support, not
every device will use both. A careful analysis of web metrics should help us
understand which operating systems are used to access the site and therefore
help determine which format of video to use.
For an up-to-date check on format support, take a look at the
articles available at http://www.jwplayer.com/html5.
Do you use images for small elements such as buttons? If so, consider
converting them to CSS3 equivalents, at least for the browsers that can
support them. It will mean a reduction in requests to the server (we're
not calling the images) and the CSS style sheet would have been cached
by the browser, so the response will be quicker. There are plenty of
examples available online; you can try Chris Coyier's Button creator at
http://css-tricks.com/examples/ButtonMaker/ or CSS Shape Generator
at http://html-generator.weebly.com/css-shape-generator.html.
Specifying only the width of images may cause a doubling or tripling of the
cycles that many browsers must process to layout the new resized page.
While each of these cycles typically take less than a millisecond, they stack
up, especially if there are multiple scalable elements on the page. Addressing
the height in the same declaration can reduce this issue:
img, video { max-width: 100%; height: auto; }
[ 64 ]
Chapter 3
If your site needs to display videos in 4:3 or 16:9 ratio format, then these
may not resize properly. We can get around this using a wrapper in HTML
that is styled to the proper dimensions, then stretch the video to fit the
following container:
<div class="wrapper-with-intrinsic-ratio">
<div class="element-to-stretch"></div>
</div>
Phew! There are certainly plenty of places where we can be tripped up if we're not
careful! Let's move on and take a look at a couple of tricks we can use to help manage
media content in our pages, beginning with a look at preloading images.
[ 65 ]
Mixing Content
Before we preview our work, it's useful to take a quick look to see how this process
works. The key to it is the class added to the body to retrieve the images before we
use them later in our code:
<body class="preload-images">
<div id="container">
...
<div id="preload">
<img src="img/img01.png" alt="Image 01" />
...
[ 66 ]
Chapter 3
If we preview the results of our work, we'll see the following four images appear:
The beauty about using this method is that we've removed the need to have to use
yet another library, such as PreloadJS. Instead, we can now choose to call it if we
decide to provide support for older browsers that don't support the body:before
trick we used in our demo.
Let's change tack and look at the reverse side of this coinlazy loading. No, this is
not some form of getting up on a Sunday morning after a particularly good night out
(terrible joke!), but a means to only load and display images at the point of viewing
them. Intrigued? I will reveal all as part of our next exercise.
[ 67 ]
Mixing Content
So far, you've seen how we can preload content. In some instances, this may not be
ideal; instead, we can do the opposite and not load content until we are about to
view it:
This process is known as lazy loading; it effectively removes the focus of loading the
images from the front (that is, on loading of the page) to the point of when we need
to see the images. To illustrate the process, we're going to use the bLazy plugin by
Bjrn Klinggard, available at http://dinbror.dk/blog/blazy/. The great thing
about this library is that it is lightweight and written in pure JavaScript, so has a zero
dependency count! Oh and did I forget it's responsive too.
Let's take a quick look at a demo (based on the original by the author), which we could
easily use as a basis for something more involved within any responsive design:
1. For the purposes of this demo, extract a copy of the lazy loading folder
within the code download that accompanies this book. It contains the
markup files, images, styling, and JavaScript needed for our demo.
2. Run the lazyloading.html file. Notice how only the first few images show?
If we scroll down, we can see the green loading image appear with the next
image appearing after a short delay.
[ 68 ]
Chapter 3
The magic in this demo centers on this code excerpt from the demo:
<div class="wrapper ratio_big-img loading">
<img class="b-lazy" src=img/placeholder.png datasrc="img/big-bear7.jpg" data-src-small="img/smallbear7.jpg" alt="Lazy load images image7" />
</div>
We kick off with a placeholder image. In this instance, we're using a 1 px square
PNG file that could be easily converted to its data-URI equivalent with little
overhead. We then use two data-src tags to flip between either the small or large
versions of the image when the window is resized.
We can test to ensure that the pictures are indeed only being loaded when visible.
In this instance, using Firefox's Developer toolbar, we can see each URL loaded
when viewed in the Console tab, as indicated in the following screenshot:
This demo is perfect as a basis to display a gallery effect on a site, particularly when
viewed on a mobile device. With a bit of reconfiguration, we could even set it to
display retina-based images; although that is something I will leave for you as a
challenge! Let's move on and cover a key topic when designing responsively: the
need to make allowances for mobile devices.
[ 69 ]
Mixing Content
[ 70 ]
Chapter 3
If you are using videos on your site, consider hosting them on YouTube. This
will save space and bandwidth costs to your site. In addition, there will be
a consistent format, which reduces the risk of any issues where videos can't
play on mobile devices.
Be careful about where you use large, high quality imageson mobile
devices, your visitors will not thank you when their data usage goes through
the roof! There are plenty of options available to reduce the image size. We
will look at two such examples later in this chapter that use Node JS to resize
and compress images automatically.
Alternatively, if you need to display images on high pixel
density displays, doubling the size but increasing the
compression will help reduce the file size. To see the effect
in action, take a look at the tutorial available at http://
greatfridays.com/blog/images-in-responsiveweb-development/. Can you see any difference in
quality between the two images used in the PayPal demo?
Always set videos to show a poster image and not to automatically play for
mobile devices. There are many options to produce images (including those
that can be automated), so there is no excuse. We'll see one example later in
this chapter, which can be easily adapted to produce an extra image to serve
as the poster.
[ 71 ]
Mixing Content
A useful tool to get to grips with is the Page Visibility or Network APIs. This
appears very simple to implement, but opens up a variety of possible uses.
One such use is to shut off any videos that are playing temporarily if a browser
window is not being displayed; this will help reduce bandwidth costs.
If your site requires a lot of vector images, you will get better results using
SVG-formatted files. These are effectively XML files that can resize with no
loss of quality.
Enough theorylet's actually try out two of these tips; we could complete them
manually, but instead we can take advantage of a task runner to complete them
automatically. Intrigued? I will explain all, beginning with a look at creating
responsive versions of our chosen images.
[ 72 ]
Chapter 3
7. Any image dropped into the src folder will be used to create three new
images, such as the example shown in the following screenshot:
[ 73 ]
Mixing Content
The automated process is now ready for use. We can drop any number of JPEG
images into the folder; three new images will be produced for each new image
dropped into the folder.
We're using the default sizes for each image as specified in the
plugin; these can be easily customized in the options for the
plugin within our gruntfile.js file.
2. Next, alter the code to add in the block for imagemin task as shown in the
following code snippet:
dest: '../responseimg/assets'
}
},
imagemin: {
jpg: { options: { progressive: false }, files: [{ expand:
true, cwd: 'assets/', src: '*.jpg', dest: 'assets/', ext: '.jpg'
}]
}
Chapter 3
4. We need to make one final change, so go ahead and alter the following line
as shown:
grunt.registerTask('default', ['simple-watch']);
5. Bring up a NodeJS command prompt and run the following command to add
the plugin and its dependencies to the package.json file:
npm install grunt-contrib-imagemin --save-dev
6. We're now ready to test our Grunt package. In the command prompt, change
the directory to the project folder, then run this command:
grunt
7. If all is well, we'll see the Grunt task run and successfully produce three new
images, which are then compressed.
The automation process is now ready for use. Although we've only put one image
through the process, we could at this point put many images through. I would
recommend running some tests to gauge how many you can safely process at the
same time, as this will be dependent on resources in your PC or Mac.
[ 75 ]
Mixing Content
Summary
Phew! We've certainly packed a lot into a small space! Let's recap on what you've
learned throughout this chapter. We kicked off with a demo of mixing video and
image content, initially to see firsthand some of the issues we face when mixing
content, but then to use some of the tips and tricks you've learned to get the pages
to behave responsively.
Having looked at a demo, we then moved onto considering some of the pitfalls of
mixing content; we saw how the large increase in responsive use has increased over
the last few years making it crucial that our designs work on a variety of platforms.
We covered a number of tips we can use to make allowances for mobile platforms in
our designs.
We ended the chapter looking at two demos using NodeJS to automate the creation
of different versions of our images and automatically shrinking them; this illustrates
how we can automate the process and save us a lot of manual effort.
Now that we have our content, we need to test it thoroughly to ensure it works
across a wide range of devices. We'll take a look at the testing process in the next
chapter, examining some of the considerations and pitfalls we need to be aware of
when working with responsive media.
[ 76 ]
www.PacktPub.com
Stay Connected: