Skip navigation
coffee with paper glasses and a pen in background

Explore the New World of JavaScript-Focused Client-Side Web Development

Learn about the scripts and tools that can help you write JavaScript client-side apps

It was fairly easy to figure out client-side web development 10 years ago. If an application needed to run consistently across browsers, HTML was dynamically generated on the server and sent to the browser for rendering. Some of the more modern applications integrated Ajax and JavaScript into the mix, but many apps worked with little or no JavaScript at all. Although I personally enjoyed working with JavaScript back then, it wasn't exactly the most popular language on the planet, and many developers avoided JavaScript entirely because of a variety of issues associated with it.

In situations in which web-based applications required "rich" client-side functionality, Adobe Flash was used because it provided animation, media services, and a host of other features that HTML, Cascading Style Sheets (CSS), and JavaScript couldn't offer. Around 5 years later, Silverlight began its rapid evolution as a client-side rich Internet application (RIA) development option. The world of RIAs looked extremely bright. Then the "RIApocalypse" occurred, and things seemed to change in the blink of an eye.

RIA frameworks such as Flash and Silverlight are certainly still viable for building different types of applications and offer some functionality that isn't quite ready yet in HTML5 or JavaScript. However, over the past 2 years, technology has quickly moved in a different direction for applications that need to reach a broad audience. As a consequence of the large increase in the number mobile devices in use, more powerful CPUs, more memory, and easier access to wireless data (and let's not forget the iPad and Apple's general view toward plug-ins), a major shift has occurred that has ushered in the rise of HTML5 and JavaScript.

Some developers like the shift; some developers hate it. Regardless of which side of the fence you're on, the shift has happened, and it has definitely had an effect on the way applications are built. My intent here is to help you negotiate the shift by providing an overview of the current state of client-side development and some popular scripts and tools that will help you build robust client-centric web applications.

Rise of the Script: Pros and Cons

JavaScript has taken center stage in web development, in response to the trend of moving to the client application functionality previously run on the server. This client-side approach provides several benefits, including fewer page postbacks, less data passed over the network, and a better overall client experience when done correctly. In many cases, the role of the web server has morphed from primarily serving HTML content to more of a focus on serving JavaScript Object Notation (JSON) data that gets processed in the browser using JavaScript. This can have a positive effect on both traditional browser applications and mobile applications because less data is sent over the wire.

Client-side web application development isn't all roses, though. Developers used to writing server-side code need to learn JavaScript and other client-side technologies and deal with cross-browser issues that can make even the best developers pull their hair out. The way that code is tested in client-side development also changes somewhat, although unit tests can be run against JavaScript using frameworks such as QUnit, Jasmine, or others. Security must also be factored into the mix as more and more functionality moves to the client and applications call back to the server to retrieve and validate data. In addition to these considerations, it's also important to take into account cross-browser issues, given the number of browsers available.

As applications move toward incorporating HTML5, it's also natural that more and more JavaScript code will be written. After all, HTML5 technologies such as geolocation, canvas, web storage, web sockets, and others rely heavily on JavaScript. As a result, careful planning must go into a project to ensure that JavaScript code is structured in a way that promotes reuse, testability, and simplified maintenance. Randomly scattering functions (I call it "function spaghetti code") across one or more script files and pages is no longer an option as the amount of JavaScript code included in an application increases. It's more important than ever for developers to study different patterns and techniques that can be used to structure code.

Even with these various challenges, the world of client-side web development is consistently improving. Although some developers choose to write all their scripts by hand, many script libraries are available that can simplify some of the client-side development challenges. Let's now examine some of those scripts and how they're being used for client-side development.

Client-Side Script Libraries and Responsive Design

The reigning king of script libraries is jQuery, which has been around since 2006. According to builtwith.com, jQuery is used in nearly 58 percent of the top 10,000 sites. More than 24 million sites are using jQuery, and that number continues to grow. If you aren't already using jQuery, should you take the time to learn it? The simple answer is "yes," but in reality the answer depends on the functionality that your application needs.
jQuery provides a cross-browser way to locate Document Object Model (DOM) nodes, handle events, perform animations, make Ajax calls, and do much more using a minimal amount of code (see the articles listed in the Learning Path for more information about jQuery and other client-side web development topics discussed in this article). No sane developer wants to worry about browser incompatibilities, and jQuery significantly eases the cross-browser headache. For example, rather than writing custom code to check what type of XmlHttpRequest object a browser supports before making an Ajax call, you can write code similar to the following to make the call and let jQuery handle the rest:

$.getJSON('/DataService/GetCustomer', { id: custID }, function(data) {
    //process data returned from the controller action
});

jQuery's core strength lies in its ability to easily select DOM elements using a small amount of code. For example, to find all li elements in divs that have a panel class on them, you can use the following jQuery selector:

var liTags = $('div.panel li');

After one or more nodes are found, you also attach events in a cross-browser manner using shortcut functions, as shown next. (You could also use bind(), on(), or other similar functions.)

liTags.click(function() {
    var li = $(this); //grab clicked item
    //do something!
});

This technique significantly minimizes the amount of code required to locate DOM nodes, the text or HTML within the nodes, or even attributes. It can also be used to animate elements, add or remove nodes, and do much more.

Also available are script libraries based on jQuery, such as jQuery UI and jQuery Mobile. jQuery UI provides a set of widgets and effects that can be used to render dialog boxes and pop-up calendars, add drag-and-drop and autocomplete functionality, and add other capabilities. jQuery Mobile is a relatively new script library that provides a simple yet robust way to build mobile-enabled websites that work well on many types of mobile devices.

When you include jQuery and jQuery Mobile scripts in a page, HTML5 data attributes can be used to define one or more mobile "pages" that resize dynamically to different device sizes. Figure 1 shows an example of using jQuery Mobile's data-role attribute to define multiple mobile pages. As the div elements in Figure 1 are processed by jQuery Mobile, they're automatically converted into pages that can be navigated to by the user.


    

In addition to script libraries such as jQuery UI and jQuery Mobile, thousands of jQuery plug-ins are also available that can be used to render grids, show charts, display images, play videos, and provide many other types of features. The large number of jQuery plug-ins plays a big part in jQuery's overall popularity.

Although jQuery is extremely popular, it can be overkill in some cases in which only a subset of the functionality it offers is needed. Future versions of jQuery will provide more modular script options that let you select the specific functionality you'd like (resulting in smaller scripts being used in an application). For now, when you need only a subset of jQuery features, you can use alternative scripts such as zepto.js or xui. Zepto.js is less than one fourth the size of jQuery yet provides many features. Zepto.js isn't designed to work on older browsers and wasn't built with Internet Explorer (IE) in mind; even so, it can be an appropriate choice in some situations. Xui is designed to work specifically with the DOM and is only around 4KB in size when compressed.

In addition to core script libraries such as jQuery, jQuery UI, jQuery Mobile, and others, several additional scripts are available to fill different client-side development needs. Because of space constraints, I won't provide an exhaustive discussion of these scripts here, but I can mention a few of the more interesting ones. Figure 2 lists some scripts that have been getting a lot of attention lately.

Script

Description
Figure 2: Scripts that can be used in web apps to simplify coding and provide core functionality and frameworks

AngularJS

AngularJS is a framework that lets you "extend" HTML's syntax to define data bindings, templates, and more.

AmplifyJS

AmplifyJS provides a unified API to access different types of data sources. For example, Ajax calls can be registered using AmplifyJS, then called throughout an application. Client-side components can also communicate using a pub/sub model.

Backbone.js

Backbone is a framework for building MVC-like JavaScript applications.

Bootstrap

Bootstrap provides UI components and interactions. Components are built with responsive design in mind, so that they adjust to different resolutions and devices.

JsRender

JsRender, a replacement for jQuery Templates, allows client-side templating that can significantly reduce the amount of JavaScript code required to convert JSON data to HTML.

KnockoutJS

Knockout provides built-in data-binding support, lets you write JavaScript code that follows the MVVM pattern, supports client-side templates, and more.

LESS

LESS adds enhancements to CSS, such as the ability to define and reuse variables, nest CSS rules, and others.

Underscore

Underscore provides many helpful utility functions for JavaScript, such as sorting arrays, grouping items, finding min and max values, and many others.

This list barely scratches the surface of what's out there, especially given that I've handpicked only a few scripts. You can find a list of some of the more popular JavaScript files currently used in websites on BuiltWith's JavaScript Libraries Growth page. Third-party companies such as Telerik, Infragistics, and others have also released script libraries.

In addition to script libraries, another topic that's relevant for today's web applications is "responsive design" and CSS media queries. More and more sites now support multiple resolutions and screen sizes. These sites "respond" dynamically to the screen size that a webpage is displayed in and fill it accordingly. Today's modern browsers support CSS media queries that can be used to target specific screen sizes. (For more information about using media queries, see the Learning Path, as well as "Working with CSS Media Queries and Media Types, Part 2." By using media queries appropriately, you can enable a website to look good in the browser, on a mobile device, and even on a tablet. The following example shows a simple CSS media query to override CSS styles when a device is 320 pixels wide:

@media screen and (max-width:320px) {
    /* override default styles here */
    nav ul > li {
    float: none;
    }
}

Feature Detection

Although nearly all modern browsers support HTML5 and CSS3 features, they don't consistently support the same set of features. Given the number of existing browsers and browser versions, knowing what features a particular browser supports is crucial. In the "old days," we'd rely on general browser detection to determine what HTML or JavaScript to load, but that doesn't work well now. We need a more fine-grained approach that determines specific features supported by a browser.

You can use the Modernizr script library to detect specific features supported by a browser. Modernizr can test for the presence of CSS3 features, canvas support, geolocation, animations, and much more. In fact, it's capable of testing more than 40 features across multiple browsers. Modernizr also adds feature-specific CSS classes, such as no-touch, cssanimations, cssgradients, and opacity to the root element as appropriate. These classes can be used to enable or disable CSS styles in an application.

The following code shows an example of using Modernzr to test for HTML5 canvas support:

if (Modernizr.canvas) {
   //get canvas and 2d context
}
else {
    //run fallback code
}

The Modernizr object shown in this code example is made available by including the modernizr.js script in your web page. After the Modernizr object is available, you can test for many different features. For example, you can test for the presence of CSS3 features such as rounded corners using the following code:

if (Modernizr.borderradius) {
   //rounded corner support is available
}

In situations in which a feature isn't available, Modernizr's YepNope functionality can be used to load a polyfill script. A polyfill is a script designed to fill in missing features in older browsers. (See the HTML5 Cross Browser Polyfills page on GitHub for a nice list of polyfills.) Following is an example of using Modernizr to detect features, then dynamically load different scripts:

Modernizr.load({
  test: Modernizr.canvas,
  yep : 'canvas.js',
  nope: 'canvas-polyfill.js'
});

This code tests for the presence of the HTML5 canvas in a browser and loads canvas.js if it's supported. If the browser doesn't support the HTML5 canvas, a polyfill script named canvas-polyfill.js is loaded instead to provide fallback functionality (note that multiple scripts can be loaded as well). Using Modernizr gives you an edge in building cutting-edge web applications that take advantage of new HTML5 and CSS3 features while still providing graceful fallbacks for older browsers.

Web Tools

One of the big complaints I hear about JavaScript is that no good tools exist for writing and debugging JavaScript code. It turns out there are actually many great editors available to help you write JavaScript. Tools such as Sublime and Notepad++ provide text-editing functionality with support for code highlighting, plug-ins, and more features, and browser-based tools such as Cloud 9 IDE or CodeMirror are also available. If you want more robust features and integrated debugging, Aptana Studio or Visual Studio 2012 provide excellent JavaScript features and the ability to set breakpoints, step through code, and other features.

Some of the best available tools are free and built directly into modern browsers. IE, Firefox, Safari, and Chrome have integrated developer tools that can be used to tweak HTML, CSS, and JavaScript live in the browser while you're viewing a site. Although my personal favorite is the Chrome Developer Tools, similar functionality is available across all the major browsers. In most cases, you access these tools by pressing F12 or via the browser's Options menu.

Figure 3 shows an example of the Chrome Developer Tools in action.

Figure 3: Using the Chrome Developer Tools to view HTML and CSS
Figure 3: Using the Chrome Developer Tools to view HTML and CSS

HTML from the page is shown on the left, and styles, margins, borders, and other metrics are on the right. You can tweak HTML and CSS directly in the tool, and changes are reflected immediately in the page. I've found this capability very helpful when I need to figure out where extra padding is coming from or get a live view of how a particular change will affect a page.

You can also debug JavaScript directly in the tool without having to leave the browser and jump back to another editor. To debug a script, select the Scripts tab, pick the script from the tree that's displayed at the left, then click in the left gutter area to set a breakpoint. Figure 4 shows an example.

Figure 4: Debugging JavaScript code using the Chrome Developer Tools
Figure 4: Debugging JavaScript code using the Chrome Developer Tools

You can step through scripts using hotkeys such as F10 or F11 (or click debug icons in the developer tools menu) and even mouse over variables or use the console to see their values, as shown in Figure 5. It goes without saying that learning how to use the browser developer tools is essential if you want to maximize your productivity as a client-side web developer.

Figure 5: Inspecting variables using browser developer tools
Figure 5: Inspecting variables using browser developer tools

In addition to editors, software vendors are releasing new tools to support animations, CSS3 features, and more. Adobe has released an early version of a tool called Adobe Edge that provides a visual editor for building complex web animations. Sencha's new Sencha Animator is another tool that can be used to build animations and interactive HTML5 and JavaScript content.

The Client-Side Future Beckons

Web development has evolved considerably in a short amount of time. Where RIAs once dominated, HTML5 and JavaScript are now taking their place because of the enhanced functionality available in modern browsers and increasing availability of mobile devices and tablets. In this article, you've seen some of the pros and cons associated with the move to HTML5 and JavaScript, as well as several libraries and technologies that can help support client-centric development. You've also seen several different tools that can be used to simplify JavaScript development and debug scripts.

After reading this article, you might wonder whether HTML5 and JavaScript offer the answer to all your web development needs going forward. Although some supposed "experts" might try to make that case, in reality it's more important than ever to use the correct language, framework, and tool for the correct job. There are plenty of cases in which RIA frameworks excel and are appropriate to use. However, the future indeed looks bright for HTML5 and JavaScript; these technologies are definitely changing the way applications are being written for both desktop and the mobile web. If you've been on the fence about learning to use the client-side web development technologies, now is a great time to take the plunge!

Learn more about JavaScript:

Learn more about jQuery:

Learn more about media queries and CSS:

Learn more about Modernizr:

Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish