Today, devices such as the AR/VR headsets Oculus Rift and HTC Vive create new uses which prelude the future of interactions with web applications. Meanwhile, data must be accessible both everywhere and quickly by a true web application which must be very optimized in execution as far as memory management.

This article aims at presenting you the trending APIs for JavaScript in 2017. Those include WebRTC, WebVR, Web and Service Workers.

Feel free to share it and leave comments if you want to add trends I haven’t mentioned or simply discuss the topic.

So let us start the list…

WEBRTC (REAL-TIME COMMUNICATIONS)

WebRTC is a standard for real-time communication between that enable video, audio and data streaming within commonly available web technologies.

By using these simple JavaScript APIs, it is possible to share data and perform teleconferencing peer-to-peer, without requiring the user to install plug-ins or any other third-party software :

getUserMedia(): audio and video capturing

MediaRecorder: audio and video recording

RTCPeerConnection: audio and video recording between users

RTCDataChannel: data streaming between users.

By using the APIs presented above, your Communication will occur directly between browsers. Then, RTCDataChannel can be much faster than WebSocket even though a relay (TURN) server is required when “hole punching” to cope with firewalls and NATs fails.

The range of browsers that support this standard is increasing. However, all browsers have not fully implemented all of its features. To help you with your implementation, you can use WebRTC adaptar.js.

For each version of the browsers supporting WebRTC, adapter.js implements the required polyfills, establishes the non-prefixed names of APIs and applies any other changes needed to make the browser run code written to the WebRTC specification.

Here is the support page for WebRTC API.

SECURITY

There are several ways a real-time communication application or plugin may compromise security. For example:

• Unencrypted media or data might be intercepted en route between browsers, or between a browser and a server.

• An application might record and distribute video or audio without the user knowing.

• Malware or viruses might be installed alongside an apparently innocuous plugin or application.

Fortunately, WebRTC has several features to avoid these problems:

• WebRTC implementations use secure protocols such as DTLS and SRTP.

• Encryption is mandatory for all WebRTC components, including signaling mechanisms.

• WebRTC is not a plugin: its components run in the browser sandbox and not in a separate process. Components do not require separate installation and are updated whenever the browser is updated.

• Camera and microphone access must be granted explicitly. And when the camera or microphone are running, this must be shown clearly on the user interface.

DEMOS

Here, you can find some demo about stream capture, peer connection, video chat…, with WebRTC: Here are some demos you can find to see several uses and implementations of Web RTC:

Simple RTCDataChannel sample

Take photo with getUserMedia()

WebRTC samples

IN SHORT

The APIs and standards of WebRTC can democratize and decentralize tools for content creation and communication. Its applications include telephony, gaming, video production, music making, news gathering and many others.

WEB VR (VIRTUAL REALITY)

WebVR is an experimental JavaScript API that enables you to access VR devices through your browser. This API allows WebGL scenes to be presented in virtual reality display on devices such as the Oculus Rift and HTC Vive. It is very interesting for interactive apps and first person games.

Have a look at these examples built with Babylon.js: a useful framework to develop with web VR. Here are other tools you can use with VR projects:

Three.js

A-Frame

React-VR

Argon.js

Awe.js

Creating web VR content is not like regular web development :

• No DOM: you can only send a canvas

• No click or touch events: use navigator.getGamepads()

• Be careful with canvas size and use getEyeParameters() to find the size of the display

• Think of using the correct frame rate: requestAnimationFrame() will help you draw to the screen at the correct rate

• Don’t forget performance: measure the time between successive frames with performance.now()

Support for web VR APIs is limited now but will grow big in the coming year.

PRACTICAL APPLICATIONS

Games, scientific applications, promotional videos, visit of the red planet, etc. These “real life” applications will give you a better idea of the potential of webVR:

Killing Floor – Incursion: compatibility Oculus Rift

Lone Echo: compatibility Oculus Rift

Comet 360: compatibility Samsung Gear VR

Mars 2030: compatibility Oculus Rift and HTC Vive

IN SHORT

WebVR alongside complementary tools makes Augmented and Virtual Reality experiences available for browsers. With a flurry of tools and Internet commission standards, this JavaScript API is worth exploring. And welcome to AR/VR in browsers!

WEB WORKERS

A web worker is a JavaScript running in the background, without affecting the performance of the page. It enables you to bring parallelism in the browser — very useful to run some heavy algorithms on a page. Then, you can continue to do whatever you want: clicking, selecting things, etc.

Workers are relatively heavy-weight and are not intended to be used in large numbers. For example, it would be inappropriate to launch one worker for each pixel of a four-megapixel picture. Generally, workers are expected to be long-lived, have a high start-up performance cost, and a high per-instance memory cost.

It’s ideal for keeping your UI responsive while also performing processor-intensive functions. However, they cannot directly interact with the DOM and communication must go through postMessage() method.

Finally, the best one-line definition that I have found is :
“Workers utilize thread-like message passing to achieve parallelism.” (Source).

Have a look at this pretty good support page for web workers.

LIFECYCLE

Let us start with a simple example:

Schema showing how web workers works

Source

Here is how it works:

1. New web worker.
worker = new Worker(scriptURL [, options ]): returns a new Worker object.

scriptURL will be fetched and executed in the background, creating a new global environment.

Options can be used to define :
a. the name of this global environment, via the name option.

b. this new global environment supports JavaScript modules via the type option (type: “module”)

i. if specified, it can also be used to specify how scriptURL is fetched through the credentials option.

2. We send “ping” to the web worker.
worker.postMessage(message [, transfer ]): clones message and transmits it to worker’s global environment. Transfers can be passed as a list of objects that are rather to be transferred than cloned.

3. It answers “pong” in serialized data.

4. Terminate the worker. worker.terminate(): aborts worker’s associated global environment.

SHARED WORKERS

Shared web workers allow any number of scripts to communicate with a single worker – even if they are being accessed by different windows, iframes or even workers.

They adhere to the same rules as their dedicated counterparts: no DOM, document or page script access, and limited read-only permission to most window properties. In addition, page scripts may only communicate with shared web workers from the same origin/domain.

You can create a shared web worker with this constructor name:

var myWorker = new SharedWorker(‘worker.js’);

Here you can find the support page for shared web workers.

Lifecycle

A simple example to use shared workers :

schema showing how shared workers works

Source

Here is how to use the shared workers:

1. sharedWorker = new SharedWorker(scriptURL [, options ]): returns a new SharedWorker object. See lifecycle of web workers for more specifications.

2. Unlike dedicated web workers, you must communicate via a “port” object and attach a message event handler. In addition, you must call the port’s start() method before using the first postMessage().

a. sharedWorker.port.addEventListener(« message », function(e) {
alert(e.data);
}, false);

b. sharedWorker.port.start(): multiple scripts can access the worker through a MessagePort object accessed using the SharedWorker.port property.

3. sharedWorker.port.postMessage(« hello world »): now messages can be sent to the worker as before, but the postMessage() method has to be invoked through the port object.

4. Optional – run the port.close() method to prevent further communication on a specific port.

Note: tabs use a shared worker to be notified of a new token.

GOOD TO KNOW

◊ Workers are not governed by the content security policy of the document (or parent worker) that created them. You can specify a content security policy by setting a Content-Security-Policy response header for the request which delivered the worker script itself. However, there is an exception where workers do inherit the CSP of the document or worker that created it. The exception to this is if the worker script’s origin is a globally unique identifier (for example, if its URL has a scheme of data or blob).

◊ Data passed between the main page and workers is copied, not shared.

◊ The page and workers do not share the same instance.

◊ You can load further scripts with importScripts() inside workers.

◊ Workers may spawn more workers if they wish.

DEMOS

These practical applications illustrate the focus on shared workers:

Array sorting with web workers

Multi tabs chatting with shared workers

IN SHORT

Web Workers are particularly suited for situations where you don’t want to keep the user waiting while some code is being processed.

The main thread could concentrate on dealing with the UI, displaying it as quickly as possible, while the Web Workers could process the data, using AJAX to communicate with the server, in the background.

Be careful with a worker, as trace memory will be increased (data transferred is copied). And communication between your application’s parts will be more complex. Then, use it with parsimony.

SERVICE WORKERS

A Service Worker looks like Shared Worker (no DOM access, global script context, not tied to a particular page). It is different since scripts can run without a page. Furthermore, it can terminate when it is not in use, and run again when needed.

Some thoughts on Service Workers:

• Functioning like a CACHE API.

• Run as a proxy with its cache.

• Have their own threads.

• Global on the browser.

• HTTPS only.

• Tied to a domain (and subdomain).

• The browser can stop the Service Worker.

Here is the support page for service workers.

LIFECYCLE

The lifecycle of a service worker is complex but you can observe the following steps :

Download: On first page-load, the service worker will be downloaded. After that, it is downloaded every 24 hours or so.

Install: Installation is attempted when the downloaded file is found to be new. Perform some tasks at install time to prepare your service worker (“install” event).

Activate: Same thing with “activate” event. It is only activated when there are no longer any pages loaded that are still using the old service worker.

Redundant: Service worker is being replaced by another one.

WORKFLOW EXAMPLE – NAVIGATION REQUEST

Let us take a basic workflow:

schema show steps by steps how you can use service workers

Source

Here is how it works:

1.The page is running

2. It communicates with service worker (with Promise)

3. The service worker uses its cache (Promise ever)

4. Cache responds with its latest version

5. The service worker updates its cache in the background via fetch

Note: the page should be updated in the concept of Progressive Rendering.

USE CASES

Make sites work faster

The service worker tries to retrieve the most up-to-date content from the network but if the network is taking too much, it will serve cached content instead.

The concept is to provide a service worker responding from cache to deliver fast responses and also updating the cache entry from the network. When the network response is ready, the UI updates automatically.

Building offline app requests cacheand fetch APIs :

• Cache APIs store requests and response.

• Fetch APIs intercept requests and serves up cached responses.

PUSH & GEOFENCING

A user can receive push notifications from a server with Push API. The service worker is necessary to handle incoming push messages.

Geofencing is a technology where you can send push notifications to users when they are in a specific area. It is a great tool for geo-marketing.

DEMOS

This awesome page will show you plenty of demos.

IN SHORT

• This API is helpful to build web application offline-first by its cache.

• With tasks in background which request a server, you can keep the cache up-to-date and update UI.

• Applying the concept of progressive rendering is helped by a service worker.

• Finally, using your web application will certainly be smoother and useful to access data everywhere.

TO CONCLUDE

In 2017, despite the fact that APIs are not well-supported by some browsers like IE, it is possible to build web applications offline-first, optimized with parallelism (web, shared and service workers). Web applications can perform teleconferencing peer-to-peer and/or be used by virtual reality system (WebRTC and WebVR). They can be very tough and user-friendly with a nice memory management.

Their other advantages include access to data everywhere and every time: big data, data-visualization, heavier applications, communication with sharing and aggregation of data, etc. Specifics issues for the developer and designer are more and more abundant. These APIs can help them achieve their common goal to provide useful and user-friendly web applications. In the end, the only limit is… your imagination

    Share: