|Updated

Top 5 Best Practices for Building HTML5 Games…In Action!

Share this article

Key Takeaways

  • Utilize a framework to handle boilerplate code and allow the developer to focus on game logic. This ensures the game runs smoothly, and handles issues like asynchronous loading and frame rate independence.
  • Ensure the game is optimized for small and touch-screen devices. This includes considering screen sizes, resolutions, aspect ratios, and input methods.
  • Regularly save the player’s progress to allow for game resumption if the webpage is closed. HTML5 DOM storage can be used for this, along with JSON for complex data structures.
  • Use a profiler tool to maintain high frame rates and locate performance bottlenecks. This helps optimize the game for a range of devices and browsers.
  • Be creative and make the most of the browser platform. This can include creating connected experiences and integrating social networking features.

HTML5 is great because it’s versatile—it’s not specific to a single use case. More important, HTML5 is ubiquitous. It’s on your PC, your phone, your slate device—for all I know, it could even be on your kitchen appliances.

Take these two properties of HTML5—versatility and ubiquity—and it should become pretty clear why so many developers are inspired by it. And, as the  proverb goes, “When developers are inspired, they usually write games.” (Okay, maybe I just made that up.)

Fortunately, deep-dive articles on HTML5 game development are now widely available. Instead, I’d like to give you an overview of things you should consider before you write a game using HTML5 and while you’re working on it.

What will you learn in this article? I’ll cover HTML5 game development frameworks, how you can reach more people by supporting smartphones and slate devices, how you should go about managing your in-game state, how to deal with performance issues, and how to make the most of the platform that is your browser.

So without further ado, here are the top 5 best practices for building HTML5 Games, in action! (“in action” added for dramatic effect).

Best practice #1: Use a framework

Writing simple games in HTML5 is easy, but as you up the ante, you need to do certain things to make sure that your game runs smoothly.

For example, when you use a lot of images, sound effects, and other resources, it will take some time for your browser to download it all from your web server. You’re in for a surprise if you don’t take this into account when writing your game. Because images and sound files are loaded asynchronously, your JavaScript code will start executing before all of your resources have been loaded. This often results in “popping” (images appearing out of the blue), and in sound effects not playing when they should. A good fix for this is to create a preloader that defers script execution until all resources have been downloaded.

Another problem you’ll likely run into is that different machines and/or browsers will run your game at different speeds. While there is nothing you can do about that, you should still make sure that animation and movement speeds are independent of the frame rate your game is running at.

Essentially, there’s a LOT of boilerplate code that every game needs in order to function properly. Fortunately, you don’t have to write all of this code yourself. There are now a variety of frameworks that allow you to focus on your game logic without having to worry about all the little (and big) things necessary to make your game run smoothly.

The only caveat with using a framework is that there are so many to choose from. Frameworks like ImpactJS for example are designed to help with almost every aspect of the game development process, while frameworks like EaselJS focus primarily on the graphics side of things. In the end, it’s up to you to pick the framework that you are most comfortable with. This may seem like a no-brainer, but in the JavaScript world, choosing a framework often implies opting into a particular style of programming.

ig.module(
    'monster'
)
.requires(
    'impact.game',
)
.defines(function(){

Monster = ig.Entity.extend({
    eyes: 42
});

});

A good example of this is ImpactJS, which not only provides abstractions for displaying graphics or playing sound effects but also introduces its own object and inheritance model as illustrated above.

Ascend Arcade

Ascended Arcade delivered three games in three months using the ImpactJS framework.

Although a lot of HTML5 games now rely on some form of framework, many developers still go down the rocky road of trying to do everything themselves. While this might be a great learning experience, if you want to get things done in a reasonable amount of time, using frameworks is definitely the way to go. A good example of this is the great work of Ascended Arcade (no longer available) who managed to release three very enjoyable (and somewhat acclaimed) games in only three months using the ImpactJS framework.

Best practice #2: Consider small- and touch-screen devices

Maybe one of the most persuasive selling points of HTML5 is that it works on desktop PCs, laptop computers, slates and even smartphones (if you haven’t seen IE9 running on Windows Phone 7 Mango, check out this video).

This unique cross-platformness (take that, Webster’s dictionary!) is intrinsic to HTML5 and often requires little additional work from the developer. However, there are a couple of things you should consider…

Spychase

SpyChase running on Windows Phone 7 Mango.

First and foremost, screen sizes can vary greatly between different device categories as can screen resolutions and aspect ratios. If you want your HTML5 games to work well on mobile devices, you should make sure they either support multiple resolutions or don’t exceed the WVGA frame size of 800×480.

Also, since most mobile devices lack the screen size to render an entire web page at once, they often employ sophisticated zooming and panning techniques that can be counterproductive when writing games. These can be turned off programmatically using the viewport meta tag. The following code snippet will cause your game’s viewport to occupy all of the available horizontal screen real estate. Setting the parameter “user-scaleable” to “no” tells the mobile browser to disable pinch-zooming, which otherwise often conflicts with finger-based game controls.

<meta name="Viewport"
content="width=device-width; user-scaleable=no; initial-scale=1.0" />

Once your game renders okay on small-screen devices, you should also take a minute to think about input. Most touch-only devices have a virtual keyboard, but they tend to take up too much screen space to be useful in controlling game characters. If strictly touch-based input is out of the question, you should build a limited virtual keyboard with only the buttons you need for your game (e.g. the arrow keys). However, it’s best to be creative with alternative means of controlling your game that don’t require additional on-screen elements. A good example of this is the game Spy Chase, where you drive a vehicle with one finger (something you should not attempt in real life).

Best practice #3: Automatically save the player’s progress

With features like site pinning, web browsers attempt to give web applications the same status as regular desktop applications. However, the idea of websites functioning as applications is rather new, and so is the notion of web pages holding client-side state. You might think twice before closing an instance of Microsoft Word, but you might not be as careful with an open web page. Most of the time, this isn’t a problem—most web pages are either stateless or maintain a record of your information on the server.

Browser games, however, are a slightly different beast. Since JavaScript code is executed on the client, HTML5 games typically keep their game state in transient memory (aka RAM). Close the browser window and your hard-earned highscore is forever lost.

Now, you might argue that a sensible person would be cautious enough not to close the game they’ve been playing for eight hours, but accidents do happen, especially when multiple tabs are involved or batteries run out of juice.

To make a long story short: When writing HTML5 games, it’s an absolute best practice to save the player’s progress regularly and allow players to resume their game when returning to a web page they’d closed.

Now where should you keep track of players’ progress? In the past, the obvious place was either a server-side database or a client-side cookie. Neither solution is especially appealing. With a server-side approach, HTTP requests have to be made whenever information needs to be stored or retrieved. The cookie approach gives you very limited space to work with and the longevity of cookies greatly depends on the browser configuration.

A much more workable solution is to use HTML5 DOM storage. DOM storage lets you save several megabytes of data per website through an interface that resembles a key-value store (or a JavaScript expando object). It’s very convenient, but in the context of HTML5 games, you might also want to remember complex data structures—something that DOM storage does not natively support.

Fortunately, modern JavaScript implementations have mechanisms built in that enable the serialization of objects into a compact notation known as JSON. Using this approach, DOM storage can also be used to remember arbitrary information. The following two helper functions illustrate how game state can be stored and retrieved using HTML5 DOM storage and the JSON features built into ECMAScript5:

function saveState(state) {
      window.localStorage.setItem("gameState", JSON.stringify(state));
}

function restoreState() {
      var state = window.localStorage.getItem("gameState");
      if (state) {
            return JSON.parse(state);
      } else {
            return null;
      }
}

Best practice #4: Use a profiler

One of the greatest challenges when developing a game is to maintain high frame rates as you add more and more features to it.

The good news is that browsers in general have become much faster over the last couple of years, and HTML5-powered games running at a constant 60 fps are already a reality.

It wasn’t easy. For Internet Explorer 9, this meant writing an all-new JavaScript engine that can use multiple CPU cores and a fully hardware-accelerated rendering pipeline based on Direct2D. In other words: If you’ve spent good money on your gaming rig, Internet Explorer 9 will make good use of it.

IE9 integrated JavaScript profile

Internet Explorer 9’s integrated JavaScript profiler helps you locate performance bottlenecks.

For simple games, this means that you don’t have to worry about performance. But since HTML5 is platform agnostic, you’re potentially developing for a whole range of devices and browsers, some of which won’t be as fast as you’d like. Even if you’re only targeting high-powered PCs (something we said we wouldn’t do, remember?), performance can still become an issue.

If you want your game to run at 60 fps, you have no more than 16 milliseconds to render any individual frame. In the time it takes for you to blink, you have to render at least 6 complete frames. Now this may seem like a daunting task…and with any non-trivial game, it certainly can be.

Luckily, there are tools that can help you. In Internet Explorer 9 (or 10 for that matter), hit the F12 key to open the developer tools. Select the “Profiler” tab and hit “Start profiling”.

Now navigate to where you feel performance should be better, give the profiler about 30 seconds to gather data, then hit “Stop profiling.” You will be presented with an overview of how much accumulated execution time is consumed by each of the functions of your game. Most of the time, you’ll find that there are a number of functions that take up the majority of the overall execution time. Optimizing these functions will give you the most bang for your buck and, when you analyze your code, slow subroutines will immediately stick out.

Don’t trust your instincts all too blindly though—code that looks slow might actually execute quite fast with today’s JavaScript engines. The best approach to optimization is to re-profile often and to always measure if the changes you make to your code actually have a positive impact on performance.

Warimals

Gaming gone social: Warimals is based on HTML5 and allows you to play alongside your Facebook friends.

Best practice #5: Be creative!

To be able to write games that run natively in your browser is pretty awesome, but what’s even cooler is that HTML5 allows you to write games that RUN IN YOUR BROWSER! Not only is HTML5 interesting from a technology point of view, a browser is also a perfect platform for gaming.

Think about it…browsers exist on many different devices, they’re (almost) always online, and they’re a tool people use to connect with each other via email, chat and social networking. As a browser game developer, you can build games that are fun and bring together people from all over the world.

If you’re new to HTML5 game development, it might be tempting to write clones of games you’ve played offline. There is absolutely nothing wrong with this approach. But if you think of your game running inside a “communication application,” there’s a good chance you’ll come up with all-new, highly creative game ideas. An interesting example of this is Warimals, one of the first HTML5-based Facebook games. In Warimals, you can play either as dogs or kittens, and you can invite your Facebook friends to play along with you. What’s not to like?

To sum up…

Thanks to the great work of framework developers and JavaScript pioneers, HTML5 has already become a fairly mature platform for writing games. This is great news, because the Web is the single most ubiquitous runtime for applications of any kind. With the right tools (many of which are conveniently integrated into Internet Explorer 9 and 10 or can be downloaded for free) and the right framework, the HTML5 game development experience can be pleasant and greatly rewarding, especially when creating connected experiences in interesting and innovative ways.

Tools to get you started:

Frequently Asked Questions about Building HTML5 Games

What are the best practices for optimizing HTML5 games for mobile devices?

When building HTML5 games, it’s crucial to optimize them for mobile devices. This involves ensuring that the game is responsive and can adapt to different screen sizes. Use viewport meta tags to control layout on mobile browsers and CSS media queries to apply different styles for different devices. Also, consider touch controls, as most mobile devices don’t have a physical keyboard. Use libraries like Hammer.js to handle touch events.

How can I improve the performance of my HTML5 game?

Performance is key in game development. To improve your HTML5 game’s performance, use WebGL for rendering when possible as it’s faster than Canvas 2D. Also, use requestAnimationFrame instead of setInterval or setTimeout for game loops. It’s more efficient and provides smoother animations. Minimize DOM manipulation and avoid memory leaks by properly managing your game objects and variables.

How can I make my HTML5 game work offline?

To make your HTML5 game work offline, you can use the Application Cache (AppCache) feature. This allows you to specify which files the browser should cache and make available to users offline. However, AppCache is deprecated in some browsers, so consider using Service Workers and the Cache API for this purpose.

What are some good resources for learning HTML5 game development?

There are many resources available online for learning HTML5 game development. Some popular ones include Mozilla Developer Network (MDN), HTML5 Game Devs Forum, and Eloquent JavaScript. There are also many books and online courses available on platforms like Udemy and Coursera.

How can I monetize my HTML5 game?

There are several ways to monetize your HTML5 game. You can sell it directly to users, offer in-app purchases, or use advertising. Platforms like Google AdSense allow you to display ads in your game. You can also consider sponsorship or licensing deals with game portals.

How can I ensure cross-browser compatibility for my HTML5 game?

To ensure cross-browser compatibility, use feature detection to check if a browser supports the features your game needs. Libraries like Modernizr can help with this. Also, test your game in different browsers and on different devices. Use polyfills for features not supported in some browsers.

How can I handle audio in HTML5 games?

Handling audio in HTML5 games can be tricky due to varying browser support. The Web Audio API provides a powerful and versatile system for controlling audio but isn’t supported in all browsers. As a fallback, you can use the HTML5 audio element. Libraries like Howler.js can help manage audio in your game.

What tools can I use to develop HTML5 games?

There are many tools available for developing HTML5 games. Some popular ones include Phaser, a fast, free, and fun open source framework, and Construct 3, a powerful and flexible game creation tool. For 3D games, Three.js and Babylon.js are good options.

How can I debug my HTML5 game?

Debugging is an essential part of game development. Use the browser’s developer tools to debug your HTML5 game. They allow you to inspect the DOM, debug JavaScript, analyze performance, and more. Also, use console.log statements for simple debugging.

How can I protect my HTML5 game’s code?

Protecting your game’s code can be challenging since JavaScript and HTML are client-side technologies. However, you can use obfuscation to make your code harder to understand. Tools like JavaScript Obfuscator can help with this. Also, use HTTPS to protect data in transit between the server and the client.

Kai JägerKai Jäger
View Author

Kai Jäger is a long-time web developer, JavaScript enthusiast, book author and now an Academic Developer Evangelist at Microsoft in Germany. When he doesn’t speak to student audiences about the virtues of HTML5, he works on his pet projects or enjoys the great Bavarian outdoors.

HTML5 Dev Center
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week