Articles in the ‘JavaScript’ Category

Going jQuery-free Part 1: Planning

Removing jQuery from your website is a big thing. We have become so reliant upon it that there are far more JavaScript plugins and modules that rely on it than that don’t. You have to be so careful when we try to remove it, or you’ll end up losing functionality. We need to plan to remove this code – we need to know what could break when we take jQuery away, and we need to know what holes we will need to plug to make our code work again.

What browsers do you need to support?

First things first, if you are going jQuery-free we need to talk about what browsers your JavaScript will support. jQuery does a lot of good things, especially for old IE, polyfilling a huge amount of code that is only available in IE9 or later. Beyond this, old Android has significant bugs and lacks support for a number of different technologies. You need to decide what the baseline will be for your usage, and apply polyfills to suit.

If you have to support IE8 I do not recommend that you ditch jQuery. IE8 doesn’t have many of the fundamentals to be considered “modern” and work without significant polyfilling in a way that modern Webkit browsers do. The Guardian uses a simple script to detect whether your browser is modern:

isModernBrowser:('querySelector'in document&&'addEventListener'in window&&'localStorage'in window&&'sessionStorage'in window&&'bind'in Function&&(('XMLHttpRequest'in window&&'withCredentials'in new XMLHttpRequest())||'XDomainRequest'in window))

This checks for the following functions:

  • querySelector
  • EventListener
  • Local Storage and Session Storage
  • Function.bind
  • Standards-based AJAX
  • CORS (Cross-origin resource scripting)

If you’re modern, The Guardian will give you everything. If not, you get a gracefully degraded experience. IE8 will fail all but the local storage part of that test, and polyfilling that much code will negate all the benefits of removing jQuery.

With some browsers, it is possible to polyfill small parts of this functionality and still remove jQuery. For example, Yell supports iOS 4 and above, which doesn’t have Function.bind, Android 2.3 doesn’t support Element.ClassList or SVG, and IE10 doesn’t support Element.data. We chose to polyfill these functions for the older browsers, but not SVG or Element.data, as these can be resolved by other techniques or just coding differently.

In the end, it’s your choice what browsers you support, but you have to be careful. There is a complete list of ECMAScript 5 functions and browsers that support them on Kangax’s Github page (as well as pages for ES6 and ES7 if you’re interested) that is incredible for helping you make this decision.

Plugins & Third-party code

jQuery made JavaScript very accessible to the novice coder because large amounts of complex code can be contained in plugins, and there are lots of them. Because jQuery is the starting point, so many bits of third-party code will need jQuery rather than using vanilla javascript and so are completely unsuitable for going jQuery-free. This can be quite a big problem.

There will be plenty of times that you will be able to find alternatives to plugins that work without jQuery. The simple way to find them is to use Google, Github, StackOverflow and Twitter to search for alternatives. I wish that there was a repository that told you the good alternatives for common jQuery plugins – but there isn’t one (note to self: do this). This can be laborious, and involve a lot of trial and error to find alternatives that match the feature set you’re looking for.

I went through this same process with my team for yell.com’s mobile site. Luckily, there was only one plugin that we needed to keep, Photoswipe – a cool plugin that creates a touch-friendly lightbox from a list of images. We looked high and low for vanilla JS alternatives that 1. were mobile-friendly, and 2. worked on Windows Phone 8 & Firefox OS and Firefox mobile. That last part was the hard bit, and I’m sad to say that we didn’t find an answer. So, we had to build this ourselves – you can see it on any business profile page on your smartphone like this one (though you’ll have to change your browser user agent to a mobile phone to see it).

TL;DR: you’ll need to find replacements for all plugins, and if you don’t, your options are to write it yourself, or drop the functionality.

Auditing your JavaScript

Once you’ve found solutions for third party code, you need to focus on your own custom code. To find out what could break, you’ll need to look over your JS and see what jQuery methods and properties are in use. You can do this manually, but I don’t fancy looking over 10,000 lines of code by hand. I asked “how can I do this” on Stack Overflow and got a great answer from Elias Dorneles:

You need a tool that understands JavaScript, like grasp. You could try to do the counting using the -o option for grasp and adding a sed filter to get only the function names: grasp '$(__).__' -e -o *.js | sed 's/.*[.]//' | uniq -c. This fails for some code for the same reasons that grep, but maybe it can help you get an estimate.

You can run this on one file, or an entire directory. Here’s what Bootstrap.js looks like (after I’ve tabulated it in excel):

Function Count
on 13
data 6
js 5
each 3
is 2
ready 2
off 2
height 2
insertAfter 1
remove 1
appendTo 1
target 1
parentsUntil 1
parents 1
width 1
one 1
trigger 1

This is the list of functions that you will have to find alternatives to in order for your JS to function correctly, along with an approximate count of the number of times a function is used. I say approximate, because in my experience, the grasp script doesn’t get everything, especially where chained functions are concerned. The good news with this set is that there aren’t many complex functions in use – the vast majority can be replaced with a line or two.

The results of this query can bring back all sorts of jQuery functions, things like .live, .die, .delegate, .browser, .size, .toggle, and other deprecated functions from over the years. These are the warning signs that the rest of your code may not be ready for a move away from jQuery, and if you get these, you should seriously consider why you’re doing this. I listed my reasons in the introduction post and there are more besides, like minimal memory footprint whilst adding Windows Phone 8 and Firefox OS support. You may end up spending a lot more effort on your code than you originally intended, just to bring it up to par with the current state of web standards. Clearly, this isn’t a bad thing, but your boss may be wondering why it’s taking so much time. For a great article on technical debt, try Paying Down your Technical Debt from Chris Atwood’s Coding Horror site.

Up next, replacing individual functions with standards-based code

That’s it for this part, in the next one, I’ll cover replacing the functions identified above with standards-compliant code to create your own min.js.

CSS3 Object-fit Polyfill

TL;DR; I’ve made a polyfill for CSS3 Object-fit. Download it from Github here: https://github.com/steveworkman/jquery-object-fit

The need for object-fit

A month ago, I was looking into creating a responsive grid full of images for a client. The width of the columns would vary depending upon device, and the dimensions and aspect ratio of the provided images could not be guaranteed.

The issue for me is keeping the images looking great, without skewing the dimensions and distorting the results, but I also needed them to expand or shrink to fit the boxes that they had been provided with.

A skewed picture

Knowing CSS, the property background-size: cover|contain would do this perfectly (See this A List Apart article for lots more detail), but this is for background images, and semantically, the images in my grid are part of the content, so should not be background images.
Looking for an equivalent, I found Object-fit: part of the CSS3 Image Values and Replaced Content spec. Unfortunately, browser support for this is very poor; this is the current browser implementation of this property:

As you can see, as of September 2012, only Opera support this feature! Side note: there is one other browser (there has to be for this to be for the spec to reach candidate recommendation) which is the HP TouchPad, not very useful for the majority of users

This isn’t going to get anyone very far, given that over 90% of all browser usage doesn’t support this feature. So, whilst browsers catch up, we have to use a polyfill to re-create this functionality with JavaScript.

Object-fit polyfill

The polyfill is based on jquery-object-fit by Simon Schmid, to which I’ve made some improvements:

  • Added support for cover
  • Fixed the implementation for IE and Firefox
  • Added feature detection so it uses the native implementation where possible
  • Made it re-calculate on resizing the browser for responsive layouts
  • Added a more tests to the suite

The results

Object-Fit tests

Object-fit grid of images

A responsive grid of images with the correct aspect ratios

What you get is a simple polyfill for object-fit which follows the spec as closely as it can. There is one main difference:

  • In a native implementation the image size remains the same and the picture within the image changes its dimensions, revealing grey letterboxed content. In the poly fill, an extra div is created around the image to take its dimensions and then the image is resized within that to provide the effect.

The source code is on github so please contribute if you can. I’ll be keeping this up-to-date so follow me @steveworkman on Twitter for the latest updates.

My thanks to Chris Mills of Opera for his articles and helping to explain how on earth all this works, and to Tab Atkins and the CSS WG for spelling it out. Hopefully there will be some more work on this feature soon. You can track the status of its implementation in Gecko (Firefox) and Webkit (Chrome et al) on their bug trackers (see links).

Please, let me know what you think in the comments and on github.

Interacting with HTML5 Video Players

HTML5 video players are incredibly useful, enabling developers to display video on non-flash devices (I’m looking at you, Apple). It’s really simple to get started with HTML5 video, but when you want to do something more complicated, there’s not much documentation. Thankfully, it’s really quite simple, and this article will show you how to use the HTML5 video JavaScript API to interact with the videos.

Basic video


This is the HTML:

<video id="firstvideo" style="width:100%" controls>
	<source src="http://mirrorblender.top-ix.org/peach/bigbuckbunny_movies/big_buck_bunny_480p_stereo.ogg" >
	<source src="http://download.blender.org/peach/bigbuckbunny_movies/BigBuckBunny_640x360.mp4" />
</source></video>

This is your standard HTML5 video player, with the standard browser video controls. The video has multiple sources so browsers that only support certain codecs (FireFox and Ogg for example) get the right video.

Let’s say you want the video to start when you click a button. That’s pretty easy, and looks like this:

var firstvideo = document.getElementById('firstvideo');
var playButton = document.getElementById('playfirstVideo');
playButton.addEventListener('click', function(e) { 
	firstvideo.play();
});
//jQuery version
$('#playfirstVideo').on('click', function(e) {
	$('#firstvideo').play();
});


And if you want to pause it:

var stopButton = document.getElementById('stopfirstVideo');
stopButton.addEventListener('click', function(e) { 
	firstvideo.pause();
});
//jQuery version
$('#stopfirstVideo').on('click', function(e) {
	$('#firstvideo').pause();
}


Subscribable events

That’s cool, you can interact with the element through JavaScript. If you’re a fan of the regular video controls, you can still access events fired by the video. The main ones you’ll be interested in are:

  • play – triggered when the video starts playing
  • playing – triggered whilst the video is playing
  • canplay – triggered when the video has been loaded and it can be played
  • pause – triggered when the video is paused
  • ended – triggered when the video has finished

There are lots of others too, a full list can be seen on the W3C demo for HTML5 video. These include events triggered when the video is seeked (skipped forward or backwards in time) and when the time on the video has changed.

It’s simple to hook these up using event listeners to see what’s going on.

Video state:

Try it out using this video, watching the label which says which event was fired last.

	var secondvideo = document.getElementById('secondvideo');
	var statelabel = document.getElementById('videoState');
	secondvideo.addEventListener('play', function(e) { // Repeat this for other events
		// The video is playing
		statelabel.innerHTML = "Playing";
	});
	// jQuery example
	var statelabel = $('#videoState');
	$('#secondvideo').on('play', function(e) { // Repeat this for other events
		// The video is playing
		statelabel.html("Playing");
	});

That's the basics, from there you can use the timing event to make a caption system (tag words with data elements and mark them when their time hits in the video).

What about YouTube?

With YouTube and other embedded video players there's no direct access to the video element, which makes interacting with videos in the way shown above very difficult.
Thankfully, the kind folks at Google have thought of this and provided an API to help us through. The whole documentation is on YouTube developers and there's a great player demo, but here's the gist of it.

There's a few gotchas you need to be aware of:

  1. You've got to be using a served web page, local files won't work.
  2. If you're trying to interact more than one YouTube embed on a page, you will need to address each one individually with unique IDs, otherwise the browser won't know which video to interacti with

Got it? Great, let's head into the code.
This first section, is the embed code needed to include the video in the page. This should be standard YouTube embedding stuff.

// The element that the player will be inserted into
<div id="ytplayer"></div>
<script>
// Load the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
 
// Replace the 'ytplayer' element with an <iframe> and
// YouTube player after the API code downloads.
var player;
function onYouTubePlayerAPIReady() {
  player = new YT.Player('ytplayer', {
    height: '390',
    width: '640',
    videoId: 'g8evyE9TuYk',
    events: {
      'onStateChange': "onytplayerStateChange"
    }
  });
}</iframe></script>

Video state:

That's your YouTube video, now we need to subscribe to the events N.B. there's no need to subscribe to the onYouTubePlayerReady event as you've effectively done this when the API loads

function onytplayerStateChange(e) {
	document.getElementById('ytvideoState').innerHTML = e.data;
}
// jQuery version
function onytplayerStateChange(e) {
	$('#ytvideoState').html(e.data);
}

As the state changes, a different value appears at the bottom. These are: unstarted (-1), ended (0), playing (1), paused (2), buffering (3), video cued (5). From there you can access any function of the YouTube JavaScript API, which mimics the HTML5 spec with a few small changes, such as the play command is playVideo() instead of just play(). Take a look at the documentation for full details about what you can do.

Vimeo too?

Yes, Vimeo can do this too. The API is similar to YouTube, but isn't quite as simple without their Frogaloop library, so have a look at their documentation for the Vimeo JavaScript API.

Summary

So, there you have it, a few bits of code to control different types of HTML5 video that are common on the web. They're really useful for counting the number of views of a video, captions, and generally making videos more interactive. Let me know what uses you come up with for it in the comments.

Node & Tell at London Web Standards #lwsnode

February 2012’s London Web Standards event at Forward London was an introduction to Node.js, the server-side javscript framework designed for high concurrency and real-time events. There were two sessions at the event, George Ornbo (@shapeshed) giving an introduction to Node, and a “Node & Tell” session, where four sets of developers came and told the gathered crowd how they’d been using Node in their work.

LWSNode - George Ornbo

Introduction to Node.js – George Ornbo

George is a front-end javascript developer who wanted a simpler way to create web apps quickly, and in a language that he knows. Enter Node.js, with its “Event driven I/O”, or better put as “Network programming with javascript”.

George fired up his browser, and gave the attendees the IP address of his laptop, which was running a simple Node.js chat server, which coped incredibly well with 100 people trying to join from their phones and laptops, showing how resilient it can be on a small laptop. We were then treated to a demo of a “Love/Hate” measure, taking a data feed from Twitter in real-time, it counted and displayed a graph of the percentage of love and hate on Twitter within the last 10 minutes. Seeing the data streaming in, and then the 30 lines of code used to create that was amazing. Node is a framework that does all the hard stuff for you, and enables you to write applications quickly and efficiently.

George then explained why it was so fast – Node works on an event loop, rather than threads. The idea is that no operation should be blocking so that Node can always keep getting http requests and fire of requests to the database or any other data sources asyncronously. It’s a big of a head scratcher to anyone who hasn’t done much high-performance javascript before, but it’s a very efficient way to program. George showed two graphs (roughly transcribed to the notes) on node performance vs apache for high concurrency and memory usage: node wipes the floor with it. Note: since this talk took place, Apache 2.4 has come out. These graphs are a bit different now but Ngix is still well ahead on speed

In summary, Node is great for high concurrency situations and for making server back-ends quickly. It’s a break from your normal programming style but is is just JavaScript when you’re over that hurdle. Give it a go!

Node and Tell Sessions

Node & Tell

All of these 4 people gave it a go and were kind enough to show us what they’d been doing.

First was Maired Buchan from Head who had made a voting system based on an Arduino and Node to collect the data. Other than that the voting machine use marble runs to capture votes, she explained that they’d tried a number of places to put the Node server to get maximum performance, eventually settling on a separate server, allowing the Arduino to just count and send a message to Node. The source code is now on GitHub.

The second talk was from Andrew Nesbitt talking about the London Node User Group (which me mentioned on and off), and showing off how he’d made the LNUG website with Node and GitHub.

The third talk was Simon Thompson talking about how he’s used Node as a prototyping language, making a drag & drop filing cabinet backed by a MongoDB. He was really impressed with how simple everything was and how little setup you needed to do before everything was working.

The final talk from Daniel Knell and Jason Grant showed a responsive web app that found interesting things to do in your local area. Using Node to help them make some of the more complex geolocation calculations, the web app is a very simple idea that is well executed. It is so good that it won first place at a recent hack day, and they finished in half the time they were given.

Node Training

If you want to learn more, go to LNUG.org or look into Remy Sharp’s training course, which is an excellent introduction to Node

London Web Standard crowd at Forward

London Web Standard crowd at Forward