# Game Development Techniques
A comprehensive reference covering essential techniques for building web-based games, compiled from MDN Web Docs.
---
## Async Scripts
**Source:** [MDN - Async Scripts for asm.js](https://developer.mozilla.org/en-US/docs/Games/Techniques/Async_scripts)
### What It Is
Async compilation allows JavaScript engines to compile asm.js code off the main thread during game loading and cache the generated machine code. This prevents recompilation on subsequent loads and gives the browser maximum flexibility to optimize the compilation process.
### How It Works
When a script is loaded asynchronously, the browser can compile it on a background thread while the main thread continues handling rendering and user interaction. The compiled code is cached so future visits skip recompilation entirely.
### When to Use It
- Medium or large games that compile asm.js code.
- Any game where startup performance matters (which is virtually all games).
- When you want the browser to cache compiled machine code across sessions.
### Code Examples
**HTML attribute approach:**
```html
```
**JavaScript dynamic creation (defaults to async):**
```javascript
const script = document.createElement("script");
script.src = "file.js";
document.body.appendChild(script);
```
**Important:** Inline scripts are never async, even with the `async` attribute. They compile and run immediately:
```html
```
**Using Blob URLs for async compilation of string-based code:**
```javascript
const blob = new Blob([codeString]);
const script = document.createElement("script");
const url = URL.createObjectURL(blob);
script.onload = script.onerror = () => URL.revokeObjectURL(url);
script.src = url;
document.body.appendChild(script);
```
The key insight is that setting `src` (rather than `innerHTML` or `textContent`) triggers async compilation.
---
## Optimizing Startup Performance
**Source:** [MDN - Optimizing Startup Performance](https://developer.mozilla.org/en-US/docs/Web/Performance/Guides/Optimizing_startup_performance)
### What It Is
A collection of strategies for improving how quickly web applications and games start up and become responsive, preventing the app, browser, or device from appearing frozen to users.
### How It Works
The core principle is avoiding blocking the main thread during startup. Work is offloaded to background threads (Web Workers), startup code is broken into small micro-tasks, and the main thread is kept free for user events and rendering. The event loop must keep cycling continuously.
### When to Use It
- Always -- this is a universal concern for all web applications and games.
- Critical for new apps since it is easier to build asynchronously from the start.
- Essential when porting native apps that expect synchronous loading and need refactoring.
### Key Techniques
**1. Script Loading with `defer` and `async`**
Prevent blocking HTML parsing:
```html
```
**2. Web Workers for Heavy Processing**
Move data fetching, decoding, and calculations to workers. This frees the main thread for UI and user events.
**3. Data Processing**
- Use browser-provided decoders (image, video) instead of custom implementations.
- Process data in parallel whenever possible, not sequentially.
- Offload asset decoding (e.g., JPEG to raw texture data) to workers.
**4. Resource Loading**
- Do not include scripts or stylesheets outside the critical rendering path in the startup HTML -- load them only when needed.
- Use resource hints: `preconnect`, `preload`.
**5. Code Size and Compression**
- Minify JavaScript files.
- Use Gzip or Brotli compression.
- Optimize and compress data files.
**6. Perceived Performance**
- Display splash screens to keep users engaged.
- Show progress indicators for heavy sites.
- Make time feel faster even if absolute duration stays the same.
**7. Emscripten Main Loop Blockers (for ported apps)**
```javascript
emscripten_push_main_loop_blocker();
// Establish functions to execute before main thread continues
// Create queue of functions called in sequence
```
### Performance Targets
| Metric | Target |
|---|---|
| Initial content appearance | 1-2 seconds |
| User-perceptible delay | 50ms or less |
| Sluggish threshold | Greater than 200ms |
Users on older or slower devices experience longer delays than developers -- always optimize accordingly.
---
## WebRTC Data Channels
**Source:** [MDN - WebRTC Data Channels](https://developer.mozilla.org/en-US/docs/Games/Techniques/WebRTC_data_channels)
### What It Is
WebRTC data channels let you send text or binary data over an active connection to a peer. In the context of games, this enables players to send data to each other for text chat or game state synchronization, without routing through a central server.
### How It Works
WebRTC establishes a peer-to-peer connection between two browsers. Once established, a data channel can be opened on that connection. Data channels come in two flavors:
**Reliable Channels:**
- Guarantee that messages arrive at the peer.
- Maintain message order -- messages arrive in the same sequence they were sent.
- Analogous to TCP sockets.
**Unreliable Channels:**
- Make no guarantees about message delivery.
- Messages may not arrive in any particular order.
- Messages may not arrive at all.
- Analogous to UDP sockets.
### When to Use It
- **Reliable channels:** Turn-based games, chat, or any scenario where every message must arrive in order.
- **Unreliable channels:** Real-time action games where low latency matters more than guaranteed delivery (e.g., position updates where stale data is worse than missing data).
### Use Cases in Games
- Player-to-player text chat communication.
- Game status information exchange between players.
- Real-time game state synchronization.
- Peer-to-peer multiplayer without a dedicated game server.
### Implementation Notes
- The WebRTC API is primarily known for audio and video communication but includes robust peer-to-peer data channel capabilities.
- Libraries are recommended to simplify implementation and work around browser differences.
- Full WebRTC documentation is available at [MDN WebRTC API](https://developer.mozilla.org/en-US/docs/Web/API/WebRTC_API).
---
## Audio for Web Games
**Source:** [MDN - Audio for Web Games](https://developer.mozilla.org/en-US/docs/Games/Techniques/Audio_for_Web_Games)
### What It Is
Audio provides feedback and atmosphere in web games. This technique covers implementing audio across desktop and mobile platforms, addressing browser differences and optimization strategies.
### How It Works
Two primary APIs are available:
1. **HTMLMediaElement** -- The standard `