Background Image

14 of the best JavaScript APIs

Enhance your sites by making the most of the newest and best JavaScript APIs.

Here's our pick of the best JavaScript APIs around right now, plus a guide to getting started using them. These will help you add new and interesting functionality to your sites and apps. A word of warning: many of these APIs are still in development, so make sure you check browser support before you start using them, and provide fallbacks where necessary. You'll find a note of the API status at time of writing at the top of each entry.

  • The best HTML APIs

01. Payment Request API

JavaScript APIs: Payment Request API

  • Status: Candidate recommendation
  • Read more: W3C summary

The first JavaScript API we're looking at is the Payment Request API.When creating an ecommerce website, lots of thought goes into improving the checkout flow to make sure the experience is as smooth and pain-free as possible. Entering payment details remains a repetitive process. If any field is slightly wrong, the whole process breaks and it needs to be started again. On the developer’s side, making sure the right validation checks are in place for each payment method is a time-consuming process.

The Payment Request API does away with this part of the checkout experience. The page can request the information it needs and the browser provides the user with the fields to enter.

The user only needs to enter their details once, and they can be used across different websites and transactions. Depending on the device, they can even use the payment methods linked to the user account, such as Google and Apple Pay.

const request = new PaymentRequest( [{ supportedMethods: "basic-card" }], { total: { label: "Total", amount: { currency: "GBP", value: 6.5 } } });

The object takes a few parameters that describe the payment that should take place. The first details the payment methods accepted. These can be different types of payment cards, as well as details for integrating with other third-party payment solutions. There is even scope to include another web application as a payment method by using the Payment Handler API.

The second is a breakdown of what is being purchased. This can be in any format that makes sense to the transaction. This also includes options for shipping costs, which can be calculated based on other factors, such as delivery address. There is also a third, optional argument to specify any extra information that needs to be collected, such as an email address or contact number.

02. CSS Layout API

JavaScript APIs: CSS Layout API

  • Status: First public working draft
  • Read more:W3C summary

As a general rule, your website layout should be left down to CSS. With JavaScript, handling changes to layout is prone to poor performance and lots of manual upkeep. But what happens if a site requires a non-standard layout? The traditional grid-like placement that CSS provides may not work for more creative design ideas.

The Layout API enables developers to create their own layout modules, much like the existing grid or flex modules in use today. By defining the rules it should work to, the API can place items anywhere within its containing element. It is the second Houdini API to make it to browsers.

Houdini introduced the concept of ‘worklets’, which work similar to web workers but are highly specialised in one activity. The Layout API works through a specific layout worklet. These get registered with the browser, which enables them to be picked up in CSS.

class MasonryWorklet { *layout(children, edges, constraints, styleMap) {}}registerLayout("masonry", MasonryWorklet);

A layout worklet has one method called layout, which deals with the positioning of elements. It runs as a generator function, enabling it to run in parallel to the rest of the page to keep everything running smoothly.

The first parameter is a reference to the immediate child elements of the one the layout is applied to. Size data is available from the second and third parameters. One provides position and dimension information about the element being styled, with the other defining the constraints the element has to work within. The final parameter describes the rest of the styles of the element, including any custom properties it may be interested in.

.el { display: layout(masonry);}

A custom module is applied by using the usual display property on an element. It uses the layout function, along with the name of the worklet.

03. Credential Management API

JavaScript APIs: Credential Management API

  • Status: Candidate Recommendation
  • Read more: W3C summary

Instead of having to remember lots of individual login details, users can log in with the credentials stored within the browser. That way, users on multiple devices can have their details follow them around without needing to log in each time.

While a browser’s autocomplete feature may reduce the friction with entering the password itself, the Credential Management API can automatically log a user in as soon as they hit the page. It can also log in using other forms of authentication, such as a public key or through an authentication provider like OpenID.

04. CSS Paint API

JavaScript APIs: CSS Paint API

  • Status: Candidate Recommendation
  • Read more: W3C guide or Google Developers summary

CSS and JavaScript are often seen as separate parts of a website – only ever coming together in small ways, such as adding a class name. Developers have few opportunities to change how the browser decides to render a page other than directly updating the DOM.

That is all set to change in the next year as a new set of specifications start to land in browsers. They provide access to the render pipeline in the browser through JavaScript, to help developers finely tune the browser’s actions to their needs.

The Houdini task force is comprised of a collection of people from browser and technology companies. They have the aim of opening up the way everything renders in the browser in a way that makes it readily approachable for developers. This includes layouts, fonts and animations.

The first specification already hitting browsers is the CSS Paint API (also known as CSS Custom Paint). This API enables you to programmatically generate an image whenever a CSS property expects one. Use JavaScript to generate dynamic backgrounds, borders and image masks and apply them in CSS without a heavy performance hit. It's about to be enabled by default in Chrome Stable.

class MyPaintWorklet { static get inputProperties() { return []; } paint(ctx, size, properties) { }}registerPaint('my-paint', MyPaintWorklet);

The Paint API uses a paint worklet to define what the browser should do each time it needs to update the screen. Each paint can use a new version of the worklet, which means that any persistent data should be stored elsewhere.

The paint callback method gets passed three values. The first is the context, which works much like a canvas context. It can be drawn upon in the same way and has most of the same capabilities, but as this can be called multiple times a second it should be kept simple.

The second value provides information about the element being painted, such as its height and width. This can be used to make sure the end result fits perfectly each time it gets used.

The final value contains all the style properties on the object. This includes any input custom properties defined within the getter. These use the Typed Object Model – another new Houdini feature that makes CSS values easier to digest in JavaScript.

The last call registers the worklet with the browser and opens it up to the CSS side.

.el { background-image: paint(my-paint);}

To use within CSS, it involves a one-line function. The passed value is the name of the effect provided when registering the worklet. The API and its associated worklet is available in Chrome and Opera, while it remains a key focus for Safari, Firefox and Samsung Internet browsers. While the specification is nearing completion, expect to see it hit those browsers soon.

Later iterations on the specification provide a mechanism for supplying arguments against the CSS function, similar to how gradients are currently defined. This enables easier customisation without having to apply custom properties. Other options, such as defining an alpha channel for layering, are also being considered.

06. Web Animations API

JavaScript APIs: Web Animations API

  • Status: Working Draft
  • Read more: W3C guide

Animation with JavaScript has historically had a bad rap. Moving elements by changing position values causes lots of repaints and results in poor performance. CSS animations are the better choice, but they are hard to manipulate on the fly.

The Web Animations API provides access to the same animation engine that powers the CSS side.

Const animation = el.animate( [ { transform: "rotate(0)" }, { transform: "rotate(360deg)" } ], 1000);

Every element has an animate method, which takes a series of keyframes plus either a settings object or a duration. This returns an animation object, which can then be updated to play, pause and adjust the playback speed.

There is added benefit coming from Houdini, with animation worklets. These work on a similar syntax to the API, but allow for finer control. They can be controlled by inputs other than time, such as scroll or touch position. This is still in development – to find out more, head over to the Chrome developer blog.

Support for the Web Animations API itself is small but is quickly growing. By using feature detection, those who have support for it can feel the benefits straight away.

07. Writable Files API

JavaScript APIs: Writable Files API

The long-term goal of web applications is to get them to be on the same level as their native counterparts. Some functionality, however, remains lacking – particularly around managing local files.

Writing files currently involves creating a download and saving to a specific directory. Saving iterations over a specific file will create multiple copies, which is not always a good experience.

The Writable Files API will provide developers with more flexibility and enable users to decide where files should be stored. This opens the door to more fully featured projects on the web, such as an online code editor or complex graphics applications.

This API is currently part of Google’s capabilities project. It’s currently in the process of gathering feedback on potential features before it hits the browser in an origin trial. Issues around security, and what kind of files can be written where, need to be ironed out before the API can be made official.

08. Generic Sensor API

  • Status: Working draft
  • Read more: W3C guide

The sensors on the devices we carry around every day are a great way of providing extra benefit to an application. Using the physical environment, such as with an accelerometer, can provide added immersion for creative experience.

If we already have events for these kinds of things, why is there a new API? Devices are constantly changing and adding new and varied sensors. To save having to create new APIs for each new sensor that comes out, the Generic Sensor API creates a simplified interface for them all.

While the API is still in development, Chrome and Firefox both include it behind flags to play around with. Other browsers have it under consideration for the future.

09. Paint Timing API

JavaScript APIs: Paint Timing API

  • Status: First Public Working Draft
  • Read more: W3C guide

Performance is a big focus this year. Getting file sizes down can help, but there is more to performance than what gets downloaded to the browser. The browser ‘paints’ its contents onscreen every time something changes. Until that first paint happens, users will be left staring at a blank screen. When it gets hung up in other details, such as downloading assets or processing JavaScript, the time to that first paint can take longer.

The Paint Timing API keeps detailed information on two events – the first paint and the first ‘contentful’ paint, which refers to something more than just styling, such as text or an image.

The PerformanceObserver interface describes what to do when these events occur. This can then be used to send the data to a server for analysis later on.

Right now, this is only available in Chrome and Opera, but other browsers such as Edge and Safari have both shown an interest and will possibly include it in the future.

10. Web Speech API

  • Try a demo
  • Status: Draft Community Group Report
  • Read more: W3C guide

This API is made of two parts – synthesis and recognition. Speech synthesis will take text supplied to it and read it out in the voice chosen by the user. The SpeechSynthesis object provides access to all the different options, including what it should say. Recognition involves taking a microphone input and understanding the words being said. The SpeechRecognition object is used to detect the speech, which will fire a ‘result’ with what it thinks the user said and how confident it is.

The synthesis side of the API is supported in all major browsers. Speech recognition support is currently limited to Chrome with a prefix, or Firefox with a flag enabled.

There are discussions to expand the recognition side to include other inputs, including WebRTC to provide real-time transcripts of video conferencing. While these are still in the early stages, it could help make webinars and online presentations more accessible and easier to reference in the future.

Generate NY 2019

Generate, the award winning conference for web designers, returns to NYC on April 24-25! Click the image to book tickets

11. Intersection Observer

  • Status: Working draft
  • Read more: W3C summary

This JavaScript API can be used to understand the visibility and position of DOM elements (known as 'targets') relative to a containing element (the 'root'). Use it to fire a callback whenever an element enters and exits a certain area. This API is best for lazy loading or infinite scroll effects.

12. Reporting Observer

  • Read more: W3C summary

Part of the Reporting API, Reporting Observers observe some types of reports from JavaScript. Use them to get notified when the browser has to intervene – for example, if it has to provide a fallback for a slow-loading font.

13. OffscreenCanvas

  • Read more: Google Developers summary

Drawing to a <canvas> is an expensive task for a browser. This new API enables you to render graphics off the main thread, without hitting the DOM.

14. Internationalisation API

  • Read more: MDN web docs

Known by the namespace Intl, the ECMAScript Internationalization API provides language-sensitive string comparison, number formatting, and date and time formatting. Use it to avoid sending heavy libraries and show dates, numbers and strings in a format that makes sense in the user’s location.

This is an edited version of an article that originally appeared in Web Designer magazine.subscribe now.

Read more:

  • The best WordPress websites
  • A coder's guide to APIs
  • Get started with the Web Audio API

Print Email

{SCPinterestShare href= layout=standard image= desc= size=small}
Web Statistics
Web Statistics