html5api
The tools available to create powerful applications on the web platform are getting better with each passing year. The HTML5 specification has added a number of useful features in new APIs that you may not have delved into yet, likely because of the lack of browser support.
随着时间的流逝,可用于在Web平台上创建功能强大的应用程序的工具越来越完善。 HTML5规范在新API中添加了许多有用的功能,可能是由于缺乏浏览器支持,所以您可能尚未研究过。
In this post, we’ll take a look at 10 HTML5 APIs that cover a whole slew of functionality and features that can help you create interactive websites, test the performance of your code, interact with a user’s device, and much more.
在本文中,我们将介绍10个HTML5 API ,这些API涵盖了一系列功能和特性,可以帮助您创建交互式网站,测试代码性能,与用户设备进行交互等等。
And as you’ll see, support for these features is probably a lot better than you might think.
如您所见,对这些功能的支持可能比您想象的要好得多。
The High Resolution Time API provides the current time in sub-millisecond resolution and such that it is not subject to system clock skew or adjustments.
高分辨率时间API以亚毫秒分辨率提供当前时间,因此不受系统时钟偏差或调整的影响。
It exposes only one method, that belongs to the window.performance
object, called now()
. It returns a DOMHighResTimeStamp
representing the current time in milliseconds. The timestamp is very accurate, with precision to a thousandth of a millisecond, allowing for accurate tests of the performance of our code.
它仅公开一种属于window.performance
对象的方法,称为now()
。 它返回一个DOMHighResTimeStamp
表示当前时间(以毫秒为单位)。 时间戳非常精确,精确到千分之一毫秒,可以对我们的代码性能进行准确的测试。
The most important feature of this method is that performance.now()
is monotonically increasing (that is, it increases consistently), so the difference between two calls will never be negative.
此方法的最重要特征是performance.now()
是单调增加的 (也就是说,它一直增加),因此两个调用之间的差永远不会为负。
The browsers that support the API are IE10, Opera 15, and Firefox 15+ without prefix. Chrome supports this API from version 20 with its “webkit” prefix, and without the prefix from version 24. More on the compatibility here.
支持API的浏览器为IE10,Opera 15和Firefox 15+(无前缀)。 Chrome支持从20版这个API以其“WebKit的”前缀,并没有从24版本更多关于兼容性的前缀这里 。
A basic example of calling this method is shown below:
调用此方法的基本示例如下所示:
var time = performance.now();
Below is a demo for you to experiment with:
以下是供您试用的演示:
See the Pen HuDAx by SitePoint (@SitePoint) on CodePen.
请参阅CodePen上的SitePoint( @SitePoint )提供的Pen HuDAx 。
To learn more about this API, you can read one of my previous articles, Discovering the High Resolution Time API.
要了解有关此API的更多信息,您可以阅读我以前的文章之一,“ 探索高分辨率时间API” 。
Another API created for testing the performance of our code is the User Timing API. With the High Resolution Time API, we can retrieve the current time in sub-millisecond resolution but it leaves us with the pain of introducing a bunch of variables in our code. The User Timing API solves this and other problems.
为测试我们的代码的性能而创建的另一个API是User Timing API 。 使用高分辨率时间API,我们可以以亚毫秒级的分辨率检索当前时间,但是这使我们难以在代码中引入大量变量。 用户计时API解决了此问题和其他问题。
It allows us to accurately measure and report the performance of a section of JavaScript code. It deals with two main concepts: mark and measure. The former represents an instant (timestamp), while the latter represents the time elapsed between two marks.
它使我们能够准确地测量和报告一段JavaScript代码的性能。 它涉及两个主要概念:标记和度量。 前者表示一个瞬间(时间戳),而后者则表示两个标记之间经过的时间。
This API exposes four methods, all belonging to the window.performance
object, that allow us to store and delete marks and measures. The mark(name)
method is used to store a timestamp with an associated name, while measure(name[, mark1[, mark2]])
can be used to store the time elapsed between two marks with the provided name.
该API公开了四个方法,所有方法都属于window.performance
对象,这些方法使我们可以存储和删除标记和度量。 mark(name)
方法用于存储具有关联名称的时间戳,而measure(name[, mark1[, mark2]])
可用于存储两个具有提供名称的标记之间经过的时间。
The desktop and mobile browsers that support the User Timing API are IE10+, Chrome 25+, and Opera 15+.
支持User Timing API的台式机和移动浏览器为IE10 +,Chrome 25+和Opera 15+。
Here is a basic example of the use of this API:
这是使用此API的基本示例:
performance.mark("startFoo");
// A time consuming function
foo();
performance.mark("endFoo");
performance.measure("durationFoo", "startFoo", "endFoo");
Here’s a demo:
这是一个演示:
See the Pen iLnAI by SitePoint (@SitePoint) on CodePen.
请参阅CodePen上的SitePoint( @SitePoint )提供的Pen iLnAI 。
For more info, take a look at my article Discovering the User Timing API.
有关更多信息,请参阅我的文章“ 发现用户计时API” 。
Page load time is one of the most important aspects of the user experience. Unfortunately, troubleshooting a slow page load is not easy because there are many contributing factors. To help with this, in addition to the APIs considered above, the W3C have proposed the Navigation Timing API.
页面加载时间是用户体验最重要的方面之一。 不幸的是,对速度缓慢的页面加载进行故障排除并不容易,因为有很多因素。 为了解决这个问题,除了上面考虑的API外,W3C还提出了Navigation Timing API 。
This API offers detailed timing information throughout the page load process accessible through the timing
property of the window.performance
object. In detail, it provides measurements related to page redirects, DNS lookup, time spent building the DOM, TCP connection establishment, and several other metrics.
这个API提供详细的整个经过访问的页面加载过程时序信息timing
的财产window.performance
对象。 详细地,它提供与页面重定向,DNS查找,建立DOM所花费的时间,TCP连接建立以及其他几个指标有关的度量。
The Navigation Timing API is currently supported in IE9+, Firefox 7+, Opera 15+, and Chrome 6+.
IE9 +,Firefox 7 +,Opera 15+和Chrome 6+ 当前支持 Navigation Timing API。
For a demonstration of this API, see this page. For more info, check out Colin Ihrig’s article Profiling Page Loads with the Navigation Timing API.
有关此API的演示, 请参阅此页面 。 有关更多信息,请查看Colin Ihrig的文章“ 使用Navigation Timing API进行页面加载分析” 。
Do you think we’re done with performance stuff? No way! Performance is one of most important concept to focus on today. Even Google has set performance as one of the main goals to achieve in 2014, according to Google Chrome programmer Eric Seidel.
您认为我们已经完成了性能方面的工作吗? 没门! 绩效是当今最重要的概念之一。 据谷歌浏览器程序员埃里克·塞德尔(Eric Seidel)称,即使是Google,也将性能作为2014年要实现的主要目标之一 。
Another API that deals with performance is the Network Information API. It helps you discover whether the user is on a metered connection, such as pay-as-you-go, and provides an estimate of bandwidth. Thanks to this information, it’s possible to change the behaviour of our pages to accommodate a user in the best way possible. For example, we could conditionally load images, videos, fonts and other resources based on the type of connection detected.
涉及性能的另一个API是Network Information API 。 它可以帮助您发现用户是否处于计费连接(例如按需付费),并提供带宽估计。 有了这些信息,就可以改变页面的行为,以最佳方式适应用户。 例如,我们可以根据检测到的连接类型有条件地加载图像,视频,字体和其他资源。
This API belongs to the connection
property of the window.navigator
object. It exposes two read-only properties: bandwidth
and metered
. The former is a number representing an estimation of the current bandwidth, while the latter is a Boolean whose value is true
if the user’s connection is subject to limitation and bandwidth usage, and false
otherwise.
该API属于window.navigator
对象的connection
属性。 它公开了两个只读属性: bandwidth
和metered
。 前者是代表当前带宽估计值的数字,而后者是布尔值,如果用户的连接受到限制和带宽使用的限制,则该值为true
,否则为false
。
Currently only Firefox 12+ and Chrome (mobile only) offer experimental support using their respective vendor prefix.
目前,只有Firefox 12+和Chrome(仅限移动设备)使用各自的供应商前缀提供实验性支持。
You can view an on-page demo of this API on csskarma. For more info, see Craig’s article, How to Use the Network Information API to Improve Responsive Websites.
您可以在csskarma上查看此API的页面演示。 有关更多信息,请参见Craig的文章“ 如何使用网络信息API改善响应性网站” 。
Another key concept that gets a lot of attention in our industry is user experience (UX). One of the APIs proposed that allows us to enhance this aspect of our websites is the Vibration API.
在我们行业中引起广泛关注的另一个关键概念是用户体验(UX)。 提出的使我们可以增强网站这一方面的API之一就是Vibration API 。
This API is designed to address use cases where touch-based feedback is required, and offers the ability to programmatically produce a vibration interacting with the mobile device’s built-in vibration hardware component. If such a component doesn’t exist, it does nothing.
此API旨在解决需要基于触摸的反馈的用例,并提供以编程方式产生与移动设备的内置振动硬件组件交互作用的振动的功能。 如果不存在这样的组件,则它什么也不做。
The Vibration API is particularly useful if you’re working with online videos or web games. For example, you could let the user’s device vibrate during the progress of the game in reaction to a particular event.
如果您正在使用在线视频或网络游戏,则振动API尤其有用。 例如,您可以让用户的设备在游戏进行过程中响应特定事件而振动。
It exposes only one method, vibrate()
, that belongs to the window.navigator
object. This method accepts one parameter specifying the duration of the vibration in milliseconds. The parameter can be either an integer or an array of integers. In the second case, it’s interpreted as alternating vibration times and pauses.
它仅公开属于window.navigator
对象的一种方法vibrate()
。 此方法接受一个参数,以毫秒为单位指定振动的持续时间。 该参数可以是整数,也可以是整数数组。 在第二种情况下,它被解释为交替的振动时间和暂停。
This API is supported in Chrome 30+, Firefox 11+, and Opera 17+.
Chrome 30 +,Firefox 11+和Opera 17+支持此API。
A basic use of this API is shown below:
该API的基本用法如下所示:
// Vibrate once for 2 seconds
navigator.vibrate(2000);
For a demonstration, visit this page in a supporting device. For more on this API, take a look at The Buzz About the Vibration API and How to Use the HTML5 Vibration API.
有关演示,请在支持设备中访问此页面 。 有关此API的更多信息,请查看有关振动API的Buzz和如何使用HTML5振动API 。
The Vibration API isn’t the only one that allows access to a device’s hardware. Another API of this type, designed with mobile devices in mind, is the Battery Status API. It allows you to inspect the state of a device’s battery and fires events about changes in battery level or status.
振动API并不是唯一允许访问设备硬件的API。 专门为移动设备设计的另一种此类API是Battery Status API 。 它使您可以检查设备电池的状态并触发有关电池电量或状态变化的事件。
The Battery Status API exposes four properties (charging
, chargingTime
, discharingTime
, and level
) and four events. The properties specify if the battery is in charge, the seconds remaining until the battery is fully charged, the seconds remaining until the battery is fully discharged, and the current level of the battery. These properties belongs to the battery
property of the window.navigator
object.
电池状态API暴露四个属性( charging
, chargingTime
, discharingTime
,和level
)以及四个事件。 这些属性指定电池是否正在充电,电池完全充满电之前剩余的秒数,电池完全充满电之前剩余的秒数以及电池的当前电量。 这些属性属于window.navigator
对象的battery
属性。
The use cases for this API are really interesting. For example, if we detect the battery is low, we could slow down or stop Ajax requests that might be occurring on a page automatically at specific intervals. Another example is to disable non-critical CSS3 and JavaScript animations, or to save data more frequently to prevent data loss when the battery reaches a critical level.
该API的用例非常有趣。 例如,如果我们检测到电池电量不足,则可以按特定的时间间隔自动减慢或停止可能在页面上发生的Ajax请求。 另一个示例是禁用非关键CSS3和JavaScript动画,或者更频繁地保存数据,以防止电池电量严重不足时丢失数据。
Currently only Firefox desktop and mobile support this API.
当前,只有Firefox桌面和移动设备支持此API。
A basic example of retrieving the current level of the battery in percentage is shown below:
下面显示了以百分比为单位获取电池当前电量的基本示例:
// Retrieves the percentage of the current level of the device's battery
var percentageLevel = navigator.battery.level * 100;
Again, here’s a demo, which will work only on a supporting device:
同样,这是一个演示,仅在支持设备上起作用:
See the Pen bFuvg by SitePoint (@SitePoint) on CodePen.
请参见CodePen上的SitePoint( @SitePoint )的Pen bFuvg 。
For more info, see Introducing the Battery Status API and How to Use the HTML5 Battery Status API
有关更多信息,请参阅电池状态API简介和如何使用HTML5电池状态API。
The Page Visibility API enables us to determine the current visibility state of the page. What this means is that we’re able to detect if our page is in the background or minimized (i.e. it’s not the currently-focused window).
页面可见性API使我们能够确定页面的当前可见性状态。 这意味着我们能够检测到我们的页面是在后台还是最小化(即它不是当前聚焦的窗口)。
This capability can help us to develop powerful, yet CPU and bandwidth efficient web applications. In fact, we can slow down or even stop a CPU and/or bandwidth consuming process if we detect the user isn’t using the page.
此功能可以帮助我们开发功能强大但CPU和带宽有效的Web应用程序。 实际上,如果我们检测到用户未使用该页面,则可以减慢甚至停止CPU和/或带宽消耗过程。
This API exposes one event, called visibilitychange
, that we can listen for to detect changes in the state of the page’s visibility, and two read-only properties, hidden
and visibilityState
. These properties belong to the document
object. hidden
is a Boolean whose value is true
if the page is not visible, and false
otherwise. visibilityState
is an enumeration that specifies the current state of the document and consists of the following values: hidden
, visible
, prerender
, and unloaded
.
该API公开了一个事件,称为visibilitychange
,我们可以侦听该事件以检测页面的可见性状态的变化,以及两个只读属性hidden
和visibilityState
。 这些属性属于document
对象。 hidden
是一个布尔,其值是true
,如果该页面是不可见的,而false
否则。 visibilityState
是一个枚举,它指定文档的当前状态,并由以下值组成: hidden
, visible
, prerender
和unloaded
。
The desktop browsers that support this API are Chrome 13+, Internet Explorer 10, Firefox 10+, Safari 7, and Opera 12.10 (source). The mobile browsers that support the API are Chrome on Android 4.0+ and Opera Mobile 12.1+ on both Android and Symbian (source).
支持此API的桌面浏览器是Chrome 13 +,Internet Explorer 10,Firefox 10 +,Safari 7和Opera 12.10( 源 )。 支持API的移动浏览器是Android 4.0+上的Chrome浏览器和Android和Symbian上的Opera Mobile 12.1+( 来源 )。
Below is a demo:
以下是一个演示:
See the Pen hcKxd by SitePoint (@SitePoint) on CodePen.
请参阅CodePen上的SitePoint( @SitePoint )的Pen hcKxd 。
For more on this API, see my article Introduction to Page Visibility API.
有关此API的更多信息,请参阅我的文章“页面可见性API简介” 。
The Fullscreen API provides a way to request fullscreen display from the user, and exit this mode when desired.
全屏API提供了一种请求用户全屏显示并在需要时退出此模式的方法。
This API exposes two methods, requestFullscreen()
and exitFullscreen()
, allowing us to request an element to become fullscreen and to exit fullscreen.
该API公开了两个方法requestFullscreen()
和exitFullscreen()
,使我们可以请求元素变为全屏并退出全屏。
It also exposes two properties, fullScreenElement
and fullScreenEnabled
, belonging to the document
object. These specify the element that has been pushed to fullscreen and if fullscreen mode is currently enabled. It also exposes one event, fullScreenEnabled
, which provides us a convenient way to listen for when fullscreen mode has been enabled or disabled.
它还公开了属于document
对象的两个属性fullScreenElement
和fullScreenEnabled
。 这些指定已推送到全屏模式的元素以及当前是否启用了全屏模式。 它还公开了一个事件fullScreenEnabled
,它为我们提供了一种方便的方式来侦听启用或禁用全屏模式时的情况。
The Fullscreen API is supported by all the major browsers, specifically: Internet Explorer 11+, Firefox 10+, Chrome 15+, Safari 5.1+, and Opera 12.10+ (source).
所有主要浏览器都支持Fullscreen API,特别是:Internet Explorer 11 +,Firefox 10 +,Chrome 15 +,Safari 5.1+和Opera 12.10+( 源 )。
For a demonstration of this API, see this page. For more info, check out Craig’s article, How to Use the HTML5 Full-Screen API (Again), from which the demo is taken.
有关此API的演示,请参阅此页面 。 有关更多信息,请查看Craig的文章“ 如何使用HTML5全屏API(再次)” ,该演示来自该文章。
The getUserMedia API provides access to multimedia streams (video, audio, or both) from local devices. This means that we can access these streams without the use of Flash or Silverlight. Some use cases for this API include real-time communication and tutorials or lesson recording.
使用getUserMedia API,可以从本地设备访问多媒体流(视频,音频或两者)。 这意味着我们无需使用Flash或Silverlight即可访问这些流。 该API的一些用例包括实时交流和教程或课程记录。
The getUserMedia API exposes just one method called getUserMedia()
. It belongs to the window.navigator
object and accepts as its parameters an object of constraints, a success callback, and a failure callback.
getUserMedia API仅公开一种称为getUserMedia()
方法。 它属于window.navigator
对象,并接受约束,成功回调和失败回调的对象作为其参数。
The getUserMedia API also allows us to have a lot of control over the requested stream. For example, we can choose to retrieve a video source at high resolution or at low resolution.
getUserMedia API还允许我们对请求的流进行很多控制。 例如,我们可以选择以高分辨率或低分辨率检索视频源。
The desktop browsers that support this API are Chrome 21+ (with -webkit prefix), Firefox 17+ (with -moz prefix), and Opera 18+. On mobile, it’s supported in Chrome 32+, Firefox 26+, and Opera 12+ (source).
支持此API的桌面浏览器是Chrome 21+(带-webkit前缀),Firefox 17+(带-moz前缀)和Opera 18+。 在移动设备上,Chrome 32 +,Firefox 26+和Opera 12+( 源 )均支持该功能。
To see a demo, visit this page in a supporting browser. For more info, see my article An Introduction to the getUserMedia API.
要观看演示, 请在支持的浏览器中访问此页面 。 有关更多信息,请参见我的文章getUserMedia API简介 。
The WebSocket API allows developers to create real-time applications by establishing socket connections between the browser and the server. This means we can establish a persistent connection between the client and the server that can exchange data at any time.
WebSocket API允许开发人员通过在浏览器和服务器之间建立套接字连接来创建实时应用程序。 这意味着我们可以在客户端和服务器之间建立持久连接,该连接可以随时交换数据。
In order to communicate using the WebSocket protocol, you need to create a WebSocket
object. As soon as the object is instantiated, the API tries to establish a connection.
为了使用WebSocket协议进行通信,您需要创建一个WebSocket
对象。 实例化对象后,API就会尝试建立连接。
The WebSocket API provides two methods: send()
, to send data to the server, and close()
, to close the connection. It also provides several attributes, some of which are event listeners. This means that we can assign them a function that is executed when an event is fired. Examples of events include an error occurring or a message arriving from the server.
WebSocket API提供了两种方法: send()
将数据发送到服务器,以及close()
关闭连接。 它还提供了几个属性,其中一些是事件侦听器。 这意味着我们可以为他们分配一个事件触发时执行的功能。 事件的示例包括发生错误或从服务器收到消息。
The WebSocket API is supported by all major browsers, specifically IE10+, Firefox 4+ (full support from version 6), Chrome 4+ (full support from version 14), Safari 5+ (full support from version 6), and Opera 11+ (full support from version 12.10), (source).
所有主流浏览器都支持WebSocket API,特别是IE10 +,Firefox 4+(版本6全面支持),Chrome 4+(版本14全面支持),Safari 5+(版本6全面支持)和Opera 11+ (版本12.10的完全支持),( 源 )。
You can read more on this API in Sandeep Panda’s article Introduction to the HTML5 WebSockets API.
您可以在Sandeep Panda的文章HTML5 WebSockets API简介中阅读有关此API的更多信息。
In this article I’ve given an overview, along with some demonstrations, of many of the APIs introduced in HTML5 in recent years. As you can see, many of them have pretty decent browser support.
在本文中,我对HTML5近年来引入的许多API进行了概述和一些演示。 如您所见,其中许多都具有相当不错的浏览器支持。
I hope this summary and the accompanying sources and demos can give you some incentive to build something cool with these new features.
我希望本摘要以及随附的源代码和演示可以激励您使用这些新功能来构建有趣的东西。
If you’ve used any of these, let us know about your experience in the comments.
如果您使用了其中任何一种,请在评论中告诉我们您的经验。
html5api