New Perspectives On Web Design

(C. Jardin) #1

CHAPTER 3 The Vanilla Web Diet


The following JavaScript shows the way to make a browser (one that sup-
ports the video element but is unable to play it) show the fallback content
instead:

if (window.addEventListener && document.querySelector) {
var v = document.querySelector('video'),
sources = v.querySelectorAll('source'),
lastsource = sources[sources.length-1];
lastsource.addEventListener('error', function(ev) {
var d = document.createElement('div');
d.innerHTML = v.innerHTML;
v.parentNode.replaceChild(d, v);
}, false);
}

What’s going on here? When a browser fails to play a video, it fires an
error handler on the last source element in the video element. So, we test
that the browser understands addEventListener() and querySelector()
(which is the standard way of jQuery’s $(), really) and then get the last
source element in the video element. If there is an error event being fired,
we create a div element and replace the video with that one.
By asking the browser what it can do, we can fix an unsatisfactory
fallback experience and make this work for everybody. Not the same expe-
rience, but still one that works. Such action needs thought and research (I
believed, for example, that the video element fires an error event instead
of the last source), but it is worthwhile as we don’t pass on our problems
to our users. “If” is a mighty construct and it makes your code better and
independent of its environment.

wRiTe aS MuCh aS neeDeD, noT The leaST PoSSible
Let’s think about what we write before we write it, instead of adding lots of small,
quick solutions.
The rise of jQuery started something of a fetish in the Web developer
community: the less code you write, the more effective you are considered
Free download pdf