Fundamentals of Cross-Platform Development (I)

Learn about a challenge that we face while cross-platform development: runtime code branching.

When developing for different platforms, the most common problem we face is how can we reuse as much code as possible and, at the same time, provide specialized implementations for details that are platform-specific. We’ll now explore some of the principles and the patterns to use when facing this challenge, such as code branching and module swapping.

Runtime code branching

The most simple and intuitive technique for providing different implementations based on the host platform is to branch our code dynamically. This requires that we have a mechanism to recognize the host platform at runtime and then dynamically switch the implementation with an if...else statement. Some generic approaches involve checking global variables that are available only on Node.js or only on the browser.

For example, we can check the existence of the window global variable. Let's modify our say-hello.js module to use this technique to provide a slightly different functionality depending on whether the module is running on the browser or on the server.

Get hands-on with 1200+ tech skills courses.