Internet Explorer之后的本机JavaScript开发

An illustration of a boy and girl with Chrome and Firefox logos playing with new technology at the park while an old man with an IE logo feeds ducks

Welcome everyone to the third and last part of this series, dedicated to the retirement of oldIE and the changes this event has in the field of front-end development. So far we covered the obsolete techniques that can be safely discarded and the HTML5 and CSS3 properties that now have full native support along the mainstream browsers. Today we will focus on native JavaScript techniques and anything else that didn’t fit in the categories mentioned before.

欢迎大家参加本系列的第3部分,也是第3部分的最后一部分,该文章专门介绍oldIE的退役以及该事件在前端开发领域中的变化。 到目前为止,我们涵盖了可以安全丢弃过时技术以及HTML5和CSS3属性,这些属性现在已经在主流浏览器中具有完全的本机支持 。 今天,我们将专注于本机JavaScript技术以及之前提到的类别中不适合的所有其他技术。

Once more, a lot of credit goes to CanIUse.com who proved to be an invaluable resource. I will also reiterate my disclaimer from last time:

再一次, CanIUse.com功不可没 ,这被证明是宝贵的资源。 我还将重申上一次的免责声明:

This article has nothing to do with the decision whether or not to abandon support for oldIE. You and you alone must take that decision based on the specific details of your website or application.

本文与是否放弃对oldIE的支持无关 。 您和您一个人必须根据您的网站或应用程序的特定详细信息来做出此决定。

With all this being said, let us proceed!

说了这么多,让我们继续吧!

1. JavaScript API (1. JavaScript APIs)

In this section we will go through quite a list of JavaScript features, APIs and functionalities. What do they all have in common? None of them could be really used on the oldIE, requiring either the use of various polyfills or their effect had to be achieved via various other frameworks and libraries (if it could be done at all). In the current context (IE11 + Edge), they have native support built into the browser, meaning they can be used straight out of the box.

在本节中,我们将详细介绍JavaScript功能,API和功能。 它们有什么共同点? 它们中的任何一个都不能真正在oldIE上使用 ,要求使用各种polyfill或必须通过各种其他框架和库来实现其效果(如果可以的话)。 在当前上下文(IE11 + Edge)中,它们在浏览器中内置了本机支持,这意味着它们可以直接使用。

Base64编码和解码(BTOA和ATOB) (Base64 encoding and decoding (btoa and atob))

Base64 is a very useful tool for web. Many of you already used it probably to embed fonts or images into CSS. Another common usage is to handle various resources that would normally interfere with transport protocols. A great example of this is Basic Access Authentication where the username:password pair is packaged using Base64 then sent to the server. Having native support for the encoding/decoding operations means they can be made a lot faster. Here are a few resources to get you started:

Base64是一个非常有用的Web工具。 你们中的许多人可能已经使用它来将字体或图像嵌入CSS。 另一种常见用法是处理通常会干扰传输协议的各种资源。 一个很好的例子是基本访问身份验证 ,其中使用Base64打包了username:password对,然后将其发送到服务器。 对编码/解码操作的本机支持意味着它们可以变得更快。 以下是一些入门资源:

Blob构建 (Blob constructing)

A Binary Large OBject or BLOB is a collection of raw data stored as a single entity in a database management system. It can be an audio clip or an image, stored in Base64 format. Or a collection of images. In many cases, Blob fields are used for data that is not as rigidly structured as to be expressed through a normal table or schema of tables, like a JSON object. Some of you might remember instead the ancestor of the Blob interface, namely the BlobBuilder. This approach has though been deprecated and it is strongly recommended that all manipulation of Blobs happen through the new interface.

二进制大对象BLOB是原始数据的集合,这些数据作为单个实体存储在数据库管理系统中。 它可以是以Base64格式存储的音频剪辑或图像。 或图像集合。 在许多情况下,Blob字段用于数据的结构不像通过普通表或表模式(如JSON对象)表示的那样严格。 你们中有些人可能还记得Blob接口的祖先,即BlobBuilder 。 尽管不建议使用此方法,但强烈建议对Blob的所有操作都通过新接口进行。

On top of that, because this collection is so similar to a file, the native interface for Blob objects has been used as base for the File() interface. As a result, there is one nice feature called “Blob URLs” that allows developers to create URLs for blob objects that can be used anywhere a file could be used. With this in mind, it’s much appreciated that native support covers all the mainstream browsers now.

最重要的是,由于此集合与文件非常相似,因此Blob对象的本机接口已用作File()接口的基础。 因此,有一个不错的功能称为“ Blob URL”,它使开发人员可以为Blob对象创建URL,这些URL可以在可以使用文件的任何位置使用。 考虑到这一点,非常感谢本机支持现在涵盖所有主流浏览器。

频道讯息 (Channel Messaging)

Normally two scripts running in different browser contexts are prohibited to communicate one to another, to avoid a lot of security pitfalls. There are times though when such a communication is not only desired, but is really necessary. This is where the Channel Messaging API comes into play. This interface allows our two scripts to communicate to each other over a two-way pipe. It’s like handing each one a walkie-talkie set on the same channel. Neat, isn’t it?

通常,禁止在不同浏览器上下文中运行的两个脚本相互通信,以避免很多安全隐患。 虽然有时不仅需要这样的交流,而且确实是必要的。 这是Channel Messaging API发挥作用的地方。 这个接口允许我们的两个脚本通过双向管道相互通信。 就像将每个对讲机交给同一频道上的对讲机一样。 整洁,不是吗?

常量和块级变量 (Constants and block-level variables)

const and let are two new ways to define data in ES6. While var defines variables with either global or function scope, the new additions have a block level scope. This means the variables created with const and let are limited in scope to inside of the pair of braces they were defined in.

constlet是在ES6中定义数据的两种新方法。 var使用全局范围或函数范围定义变量时,新添加的内容具有块级范围。 这意味着用constlet创建的变量的作用域仅限于定义它们的一对大括号内。

While let defines a variable that (excepting scope) behaves identical to classic variable, a constant (const) is a read-only reference to a certain value. It can’t be reassigned, it can’t be redefined and it can’t share the same name as any other variable or function in the same scope. The only exception is when the constant is an object with its own attributes. These attributes are not protected from change and behave like normal variables.

尽管let定义了一个变量(除范围外)与经典变量具有相同的行为,但常量( const )是对特定值的只读引用。 它不能被重新分配,不能被重新定义,并且不能与同一范围内的任何其他变量或函数共享相同的名称。 唯一的例外是,当常量是具有自己属性的对象时。 这些属性没有受到更改的保护,其行为类似于普通变量。

This being said, have a look at the proper way to use constants and block-level variables in your code:

话虽如此,请看看在代码中使用常量和块级变量的正确方法:

控制台记录 (Console Logging)

Most front-end developers would agree that the web console is one of the most useful tools to have at hand when your scripts are not behaving as they should. Yet Internet Explorer, by its nature, was pretty slow to integrate it into their code, with only version 10 starting to provide full support. Now, with the oldIE retired, there is nothing stopping us from making the most of this feature. And if you need to refresh your knowledge or even to discover new ways to use the console, have a look at the specs below:

大多数前端开发人员都会同意,当脚本无法正常运行时,Web控制台是手头上最有用的工具之一。 然而,Internet Explorer从本质上来说,将其集成到其代码中的过程相当缓慢,只有第10版才开始提供全面支持。 现在,随着oldIE的停用 ,没有什么可以阻止我们充分利用此功能。 并且,如果您需要更新知识甚至发现使用控制台的新方法,请查看以下规格:

跨域资源共享 (Cross-Origin Resource Sharing)

Cross-origin resource sharing (CORS) is an HTML5 API that enables the request of resources from outside of its own domain. It describes a set of HTTP headers that permit browsers and servers to request remote resources when a specific permission is granted. The following resources are a good starting point in learning how to use this feature correctly:

跨域资源共享(CORS)是HTML5 API,可从其自己的域外部请求资源。 它描述了一组HTTP标头,这些标头允许浏览器和服务器在授予特定权限时请求远程资源。 以下资源是学习如何正确使用此功能的良好起点:

Web密码学API (Web Cryptography API)

Today, security and privacy are two of the most sought after features of any app, which means that good (and fast) cryptography is really appreciated. Now all mainstream browsers have consistent support for the Web Cryptography API, with the exception of IE11 (which implements the old version of the spec) and Safari (which requires the crypto.webkitSubtle prefix). Fortunately, some specific functionalities (like the generation of random values) are better implemented. As a result, it’s easier than ever to implement elements of cryptography with native support. Here are a few guidelines on how to do it properly:

今天,安全性和隐私性是任何应用程序中最受欢迎的两个功能,这意味着良好(快速)的加密技术确实受到人们的赞赏。 现在,除IE11(实现规范的旧版本)和Safari(要求crypto.webkitSubtle前缀)外,所有主流浏览器都对Web密码API提供一致的支持。 幸运的是,可以更好地实现某些特定功能(例如随机值的生成)。 结果,通过本机支持实现加密元素比以往任何时候都容易。 以下是一些有关如何正确执行操作的准则:

国际化 (Internationalization)

Nowadays the ubiquity of Internet access means that visitors to your websites can come from all around the world. As people are more trusting to things familiar to them, it is a good practice to present all your information both in their language and in a format they are accustomed to. That’s where you need Internationalization (also known as i18n) and Localization (or L10n). Does this sound like gibberish to you? Let’s quote Aurelio De Rosa from his article on How to Implement Internationalization (i18n) in JavaScript:

如今,互联网无处不在意味着您网站的访问者可能来自世界各地。 由于人们越来越相信自己熟悉的事物,因此,以他们的语言和习惯的格式来显示您的所有信息是一种很好的做法。 那就是您需要国际化 (也称为i18n )和本地化 (或L10n )的地方。 这听起来像胡言乱语吗? 让我们引用Aurelio De Rosa的文章“ 如何在JavaScript中实现国际化(i18n)”

Internationalization (also known as i18n) is the process of creating or transforming products and services so that they can easily be adapted to specific local languages and cultures. Localization (also known as L10n) is the process of adapting internationalized software for a specific region or language. In other words, internationalization is the process of adapting your software to support multiple cultures (currency format, date format, and so on), while localization is the process of implementing one or more culture.

国际化 (也称为i18n)是创建或转换产品和服务的过程,以便可以轻松地使其适应特定的本地语言和文化。 本地化 (也称为L10n)是使国际化软件适应特定地区或语言的过程。 换句话说,国际化是使您的软件适应多种文化(货币格式,日期格式等)的过程,而本地化是实现一种或多种文化的过程。

Browser support is slightly better than what it was at the beginning of the year, with Safari v10 joining the ranks in September. Sounds interesting enough? Here are some resources to put you on the right path:

Safari v10在9月份加入了浏览器的行列,与年初相比,浏览器的支持要好一些。 听起来够有趣吗? 这里有一些资源可以帮助您走上正确的道路:

处理媒体查询 (Handling media queries)

Responsive web design is the current standard for performant websites and the key feature that makes it possible is the existence of media queries. matchmedia brings media queries from CSS into JavaScript giving developers a lot more flexibility in optimizing the content for all sort of devices. A good example would be handling the change from portrait to landscape mode and back for mobile phones and tablets. While there is an API that handles detection of device orientation, the support is partial for most browsers, while only Microsoft Edge provides full support. Here are some resources to get you started on this topic:

响应式网页设计是高性能网站的当前标准,而使之成为可能的关键功能是媒体查询的存在。 matchmedia将媒体查询从CSS引入JavaScript,从而为开发人员提供了更大的灵活性,可以优化各种设备的内容。 一个很好的例子是处理从纵向模式到横向模式的转换,再回到手机和平板电脑的转换。 尽管有一个用于处理设备方向检测的API,但是大多数浏览器仅部分支持该功能,而只有Microsoft Edge提供了完全支持。 这里有一些资源可以帮助您开始使用该主题:

媒体源扩展 (Media Source Extensions)

Media Source Extensions (MSE) add extra functionality to the video and audio elements without using plug-ins. This gives you such things as adaptive media streaming, live streaming, splicing videos, and video editing. YouTube has been using MSE with its HTML5 player since September 2013. Browser support is also quite good, with only iOS Safari and Opera Mini missing this functionality. IE11 has full support only when used on Windows 8+. Unfortunately, IE11/Win7 users are not able to benefit from this technology. Whether you are just curious or really want to start working with this API, you will find the following resources quite useful:

媒体源扩展(MSE)在不使用插件的情况下为视频和音频元素添加了附加功能。 这为您提供了诸如自适应媒体流,实时流,拼接视频和视频编辑之类的功能。 自2013年9月以来,YouTube一直在其HTML5播放器上使用MSE。浏览器支持也相当不错,只有iOS Safari和Opera Mini缺少此功能。 IE11仅在Windows 8+上使用时才具有完全支持。 不幸的是,IE11 / Win7用户无法从这项技术中受益。 无论您是好奇还是真的想开始使用此API,您都会发现以下资源非常有用:

突变观察者 (Mutation Observers)

JavaScript apps are growing more and more complex every day. As a developer, you need to stay in control over the changes that happen on the page, especially about the times the DOM tree changes or “mutates”. The need for this sort of monitoring is not new and indeed there has already been a solution — mutation events. The problem with this interface is that, as events, they are both synchronous (are fired when called and may prevent other events from firing) and must be captured or bubbled through the DOM. This in turn, can trigger other events overloading the JavaScript thread, and generating, in some special cases, entire cascade failures, causing your browser to crash into pieces.

JavaScript应用每天都在变得越来越复杂。 作为开发人员,您需要控制页面上发生的更改,尤其是在DOM树更改或“变异”的时间。 对这种监视的需求并不是新的,确实已经有了解决方案-突变事件。 此接口的问题在于,作为事件,它们都是同步的(在调用时被触发,并且可能阻止其他事件触发),并且必须通过DOM捕获或冒泡。 反过来,这可能会触发其他事件,使JavaScript线程超载,并在某些特殊情况下生成整个级联故障,从而导致浏览器崩溃。

As a result, mutation events have been deprecated and replaced with mutation observers. What’s the difference, you might ask? First and most importantly, observers are asynchronous. They don’t hold back your scripts from running. Instead of being fired at every mutation, they deliver a batch of results after the main activity is complete. More so, you can fine-tune observers to observe either all changes to a node or just specific categories of changes (like only changes to the list of children or just to the attributes and so on). Start learning how to do it with the following resources:

结果,不赞成使用突变事件,而用突变观察者代替。 您可能会问有什么区别? 首先也是最重要的是,观察者是异步的。 它们不会阻止您的脚本运行。 在主要活动完成后,它们会发出一批结果,而不是每次突变都被触发。 更重要的是,您可以微调观察者以观察节点的所有更改,或者仅观察特定的更改类别(例如仅更改子列表或仅更改属性,等等)。 使用以下资源开始学习如何做:

页面可见度 (Page Visibility)

Tab browsing changed the way we interact with the web. It’s not uncommon for many people to have dozens of pages open at the same time. Each of these pages does their own thing, runs their scripts, downloads what resources they have and so on. Even though there can be only one tab active at a given time, all open pages are consuming CPU time and bandwidth. Some apps might be sending and receiving updates across the connection on a periodic basis. Yet, if you don’t have that app in the active tab, does it need to update every X seconds in the background? Seems kind of wasteful, doesn’t it? Especially on mobile devices and data plans, where every resource is at a premium.

标签浏览改变了我们与网络互动的方式。 许多人同时打开数十个页面并不少见。 这些页面中的每个页面都做自己的事情,运行他们的脚本,下载他们拥有的资源等等。 即使在给定时间只有一个选项卡处于活动状态,所有打开的页面仍在消耗CPU时间和带宽。 某些应用可能会定期通过连接发送和接收更新。 但是,如果您在活动选项卡中没有该应用,那么它是否需要在后台每隔X秒更新一次? 看起来有点浪费,不是吗? 尤其是在移动设备和数据计划上,其中每种资源都很宝贵。

This is where the Page Visibility API comes into play. This interface allows developers to know whether their app is in an active tab or in the background. Let’s take the case of the app doing updates that I mentioned earlier. With the Page Visibility API you can detect when the app is in the background and instead of doing the updates every 5 or 10 seconds, you do it every 60 seconds or even less. As soon as the page is visible again, you can switch back to the normal rate of updates. Pretty cool, isn’t it?

这是Page Visibility API发挥作用的地方。 该界面使开发人员可以知道他们的应用是在活动选项卡中还是在后台。 让我们以应用程序执行我前面提到的更新为例。 使用Page Visibility API,您可以检测应用程序何时在后台运行,而不是每5或10秒进行一次更新,而是每60秒或更短的时间进行一次更新。 页面再次显示后,您可以切换回正常的更新速率。 很酷,不是吗?

So what are you waiting for? Have a look at the following guides and start your apps for page visibility. Your users will thank you for it:

那你还在等什么? 请查看以下指南,并启动您的应用以获取页面可见性。 您的用户将为此感谢您:

页面过渡事件 (Page Transition Events)

Did you ever use a web form that, when you tried to move away or close the page, it popped a message saying you have unsaved data? It is pretty common nowadays with pages where you change settings, profile details, etc. How do the scripts in the page know that you want to leave? They listen to the pagehide event.

您是否曾经使用过一种Web表单,当您尝试移开或关闭页面时,它弹出一条消息,提示您尚未保存数据? 如今,在页面上您可以更改设置,配置文件详细信息等,这很常见。页面中的脚本如何知道您要离开? 他们听pagehide事件。

pagehide and its partner pageshow are the main protagonists of the Page Transition Events. We’ve seen above what the first one is mainly used for. The main use for pageshow is to determine whether a page has been loaded from cache or straight from the server. Not the most common of uses, but, if you have need for either functionality, have a look at the resources below:

pagehide及其合作伙伴pageshow是Page Transition Events的主要角色。 我们已经在上面看到了第一个的主要用途。 pageshow的主要用途是确定是从缓存中加载页面还是直接从服务器中加载页面。 这不是最常见的用法,但是,如果您需要这两种功能,请查看以下资源:

requestAnimationFrame (requestAnimationFrame)

Animation on web has come a long way, from the early days of <marquee> and <blink>, through to animated GIFs, jQuery effects, to current CSS, SVG, canvas and WebGL animations. A constant among all these methods is the need to control the flow of the animation and to make it as smooth as possible.

<marquee><blink>的早期发展到动画GIF,jQuery效果,再到当前CSS,SVG,canvas和WebGL动画,网络动画已经走了很长一段路。 在所有这些方法中,始终需要控制动画的流程并使其尽可能平滑。

The initial method used setInterval and setTimeout to control the steps of the animation. The problem is that the results are not reliably consistent and the animation is often rough. That’s why a new interface was conceived — requestAnimationFrame. The main advantage of this approach is that the browser has the freedom to match the requests to its own painting cycles, smoothing down visibly the animations. Together with its counterpart, cancelAnimationFrame, these two methods are the base of modern JavaScript animation.

初始方法使用setIntervalsetTimeout来控制动画的步骤。 问题是结果不能可靠地保持一致,并且动画通常很粗糙。 这就是为什么要构思一个新接口requestAnimationFrame 。 这种方法的主要优点是浏览器可以自由地将请求与其自己的绘画周期进行匹配,从而使动画看起来更加平滑。 连同其对应的cancelAnimationFrame ,这两个方法是现代JavaScript动画的基础。

As usual, below are some resources to get you started in mastering this functionality.

与往常一样,以下是一些资源,可帮助您开始掌握此功能。

定时API (Timing APIs)

Online performance is the topic of the day and everyone tries their best to slim down on the resources, to optimize the scripts and make the best use of all their tools at their disposal. There are two main ways to approach this topic: network performance (how fast the site and resources are delivered) and user performance (how fast the application itself performs).

在线性能是当今的主题,每个人都尽力减少资源,优化脚本并充分利用所有可用工具。 解决此主题的方法主要有两种:网络性能(交付站点和资源的速度)和用户性能(应用程序本身执行的速度)。

Network performance is serviced by two APIs: Navigation Timing and Resource Timing. Both of them give all sorts of info related to network performance, like DNS, CDN, request and response time, etc. The only difference is that Navigation Timing targets the HTML page itself, while Resource Timing deals with all the other resources (images, scripts, media, etc.)

网络性能由两个API提供服务: Navigation TimingResource Timing 。 它们都提供与网络性能有关的各种信息,例如DNS,CDN,请求和响应时间等。唯一的区别是, Navigation Timing针对HTML页面本身,而Resource Timing处理所有其他资源(图像,脚本,媒体等)

On the user performance end we have one API: User Timing. This API deals with two main concepts, called Mark (a highly detailed timestamp) and Measure (the interval between two Marks). Tinkering around with these concepts allows developers to measure how fast their code is running and to identify places that require optimization. Unfortunately, this API is still not supported on Safari so a polyfill might be required.

在用户性能方面,我们有一个API: User Timing 。 该API处理两个主要概念,称为Mark (高度详细的时间戳)和Measure (两个标记之间的间隔)。 通过修改这些概念,开发人员可以衡量其代码的运行速度,并确定需要优化的地方。 不幸的是,Safari仍不支持此API,因此可能需要使用polyfill。

Mastering the use of these interfaces becomes a vital skill in the quest to ensure optimal performance of your website or app. That’s why we’re giving you some materials to start learning:

掌握这些界面的使用对于确保网站或应用的最佳性能至关重要。 因此,我们向您提供一些开始学习的材料:

类型数组 (Typed Arrays)

JavaScript typed arrays are array-like objects and provide a mechanism for accessing raw binary data. For maximum flexibility and efficiency, the implementation is split along two concepts: buffers (chunks of raw data) and views (who provide a context where the buffer data can be interpreted). There are a number of web APIs that use typed arrays, such as WebGL, Canvas 2D, XMLHttpRequest2, File, Media Source or Binary WebSockets. If your code deals with such technologies, you might be interested in the resources below:

JavaScript类型的数组是类似于数组的对象,并提供了一种用于访问原始二进制数据的机制。 为了获得最大的灵活性和效率,将实现分为两个概念:缓冲区(原始数据块)和视图(它们提供可以解释缓冲区数据的上下文)。 有许多使用类型化数组的Web API,例如WebGL,Canvas 2D,XMLHttpRequest2,File,Media Source或Binary WebSockets。 如果您的代码使用了此类技术,那么您可能会对以下资源感兴趣:

Web套接字 (WebSockets)

We talked earlier about Channel Messaging and how it enables two different scripts to communicate directly one to another. WebSockets is similar and a lot more than that. Using this API creates a persistent communication channel between the browser and the web server.

前面我们讨论了通道消息传递,以及它如何使两个不同的脚本直接相互通信。 WebSockets与之相似,并且远不止于此。 使用此API可以在浏览器和Web服务器之间创建持久的通信通道。

Just like HTTP, the WebSocket protocol has two versions: unsecured (ws://...) and secured (wss://...). It also takes into account proxy servers and firewalls, by opening tunnels through them. In fact, a WebSocket connection starts as a normal HTTP connection, ensuring compatibility with the existing infrastructure.

就像HTTP一样,WebSocket协议有两个版本:不安全( ws://... )和安全( wss://... )。 通过打开通过它们的隧道,它还考虑了代理服务器和防火墙。 实际上,WebSocket连接从普通的HTTP连接开始,以确保与现有基础结构的兼容性。

WebSockets are a fascinating piece of technology (they even have a dedicated website), there is a lot to learn about them. To get you started, here are a few selected resources:

WebSockets是一项引人入胜的技术(甚至有专门的网站),还有很多要学习的知识。 为了帮助您入门,这里有一些精选资源:

网络工作者 (Web Workers)

By default, all JavaScript tasks run into the same thread. This means that all scripts in a page have to share the same queue for processing time. That was nice and simple when processors had a single core. But modern CPUs have at least dual cores, reaching out to 4, 6 or 8 on some models. Wouldn’t be nice if some tasks could be moved into separate threads that could be processed by the extra cores available? That’s what Web Workers were invented for.

默认情况下,所有JavaScript任务都运行在同一线程中。 这意味着页面中的所有脚本必须共享相同的队列以进行处理。 当处理器只有一个内核时,这很好而又简单。 但是现代CPU至少具有双核,在某些型号上可以达到4、6或8。 如果可以将某些任务移到可以由可用的额外核心处理的单独线程中,那会不会很好? 这就是Web Worker的发明目的。

Using the Web Workers API, a developer can delegate a named script file to a worker that runs in a separate thread. The worker answers only to the script that created it, communicating both ways via messages, can run XMLHttpRequest calls and does not interact with the DOM or some of the default methods and properties of the window object. In the exception category we can mention WebSockets (one can assign the management of the WebSocket connection to a worker) or data storage mechanism like IndexedDB. There’s nothing like having your own minions handling secondary tasks while the main thread focuses on the running the entire app.

使用Web Workers API,开发人员可以将命名脚本文件委派给在单独线程中运行的worker。 工作者仅对创建脚本的脚本进行回答,通过消息以两种方式进行通信,可以运行XMLHttpRequest调用,并且不与DOM或window对象的某些默认方法和属性进行交互。 在例外类别中,我们可以提及WebSockets (可以将WebSocket连接的管理分配给工作程序)或诸如IndexedDB数据存储机制。 没有什么比让自己的奴才处理次要任务更重要了,而主线程则专注于运行整个应用程序。

To get you started with this functionality (including a list of functions and classes available to web workers), check the resources below:

要使您开始使用此功能(包括可用于Web Worker的功能和类的列表),请检查以下资源:

XMLHttpRequest的高级功能 (XMLHttpRequest advanced features)

The adoption of XMLHttpRequest heralded a new age in web development. Data could now be exchanged between browser and server without having to reload the entire page. AJAX was the new standard that allowed the existence of one-page applications that everyone loves today.

XMLHttpRequest的采用预示了Web开发的新纪元。 现在可以在浏览器和服务器之间交换数据,而不必重新加载整个页面。 AJAX是新标准,允许存在当今每个人都喜欢的一页应用程序。

It is only normal that such a useful technology will be advanced even further. This is how XHR gained new functionality like file uploads, information on the transfer progress or the ability to send form data directly. And all these functionalities (with minor exceptions in the case of IE11 or old versions of Android) are supported on the mainstream browsers after the retirement of oldIE.

这种有用的技术将被进一步推广是很正常的。 这就是XHR获得新功能的方式,例如文件上载,传输进度信息或直接发送表单数据的功能。 在oldIE退役后,主流浏览器都支持所有这些功能(IE11或旧版本的Android除外)。

For more details, feel free to peruse the following resources:

有关更多详细信息,请随时阅读以下资源:

2.杂项功能 (2. Miscellaneous features)

Modern web is not just HTML, CSS and JavaScript. There are many unseen (and unsung) heroes toiling behind the scenes to make our online experience as great as possible. Below, we will discuss several such features that, just as the ones above, couldn’t be used on the oldIE browsers (who were notorious for their security holes and lack of support for modern features).

现代网络不仅仅是HTML,CSS和JavaScript。 为了让我们的在线体验尽可能的出色,有许多看不见(和鲜为人知)的英雄在幕后奋斗。 下面,我们将讨论几种与上述功能相同的功能,这些功能无法在旧的IE浏览器上使用(这些浏览器因其安全漏洞和对现代功能的支持而臭名昭著)。

使用“异步”和“延迟”进行非阻塞JavaScript加载 (Non-blocking JavaScript loading with “async” and “defer”)

Every web developer learns that scripts are “load-blocking” and will hold the entire page hostage until they finish loading. We all remember the recommendation to load jQuery right before the </body>. Such approach is useless though in the case of single page apps, where all the behavior of the website is driven by JavaScript. Which sends us back to square one.

每个Web开发人员都知道脚本是“负载阻塞”的,并且将整个页面当作人质,直到脚本完成加载。 我们都记得在</body>之前加载jQuery的建议。 尽管对于单页应用程序(该网站的所有行为均由JavaScript驱动)而言,这种方法毫无用处。 这使我们回到了第一方。

But the truth is that in most cases your website or app needs just a part of all the JavaScript it loads. The rest will be needed down the road or they are doing things that don’t influence the DOM. The obvious approach is to load only the critical scripts the normal way and the rest in a manner that won’t affect the app in a negative way. And indeed, there are two such loading methods.

但事实是,在大多数情况下,您的网站或应用程序只需要其加载的所有JavaScript的一部分。 其余的将需要使用,否则它们正在做的事情不会影响DOM。 一种明显的方法是仅以正常方式加载关键脚本,其余部分以不会对应用程序产生负面影响的方式加载。 实际上,有两种这样的加载方法。

The first one is using the defer attribute, used to mark a script that won’t affect the DOM and is meant to be executed after the document has been parsed. In most cases these scripts handle user interactions, making them safe to load this way. The second one uses the async attribute and marks a script that, while loaded in parallel, will execute as soon as it is downloaded. There is no guarantee though that the loading order will be the same as the execution order.

第一个是使用defer属性,该属性用于标记不会影响DOM的脚本,并打算在文档解析后执行。 在大多数情况下,这些脚本处理用户交互,因此可以安全地以这种方式加载。 第二个脚本使用async属性并标记一个脚本,该脚本在并行加载时将在下载后立即执行。 尽管不能保证加载顺序将与执行顺序相同。

With all the benefits these two arguments bring, they are becoming an important tool in improving the performance of websites and apps. Have a look at the resources below to learn more about how and when to use this technique:

有了这两个论点带来的所有好处,它们就成为提高网站和应用程序性能的重要工具。 请查看下面的资源,以了解有关如何以及何时使用此技术的更多信息:

内容安全政策 (Content Security Policy)

From the beginning, the security on the web was built around the model of “same origin”, meaning that only scripts from the same domain can interact with a given page. Over time though, we had to integrate third party scripts into our pages: JavaScript libraries from CDNs, social media widgets from Facebook, Google+ or Twitter and other similar cases. This means that we opened the gates and allowed “guest” scripts to run into our metaphorical courtyards. The problem comes when malicious scripts slither inside as well and are being executed just like the rest – an attack method we all know as Cross-Site Scripting or XSS.

从一开始,网络安全就建立在“相同来源”模型的基础上,这意味着只有来自相同域的脚本才能与给定页面进行交互。 但是随着时间的流逝,我们不得不将第三方脚本集成到我们的页面中:来自CDNJavaScript库,来自Facebook,Google +或Twitter的社交媒体小部件以及其他类似情况。 这意味着我们打开了大门,并允许“来宾”脚本进入我们的隐喻庭院。 问题出在恶意脚本也进入内部并像其他脚本一样被执行时,这就是众所周知的跨站点脚本XSS攻击方法。

Content Security Policy is the main weapon in the fight against XSS. This mechanism contains a set of policies and directives that specify which scripts are allowed to be executed, from where it can load resources, if it can run inline styles or scripts and so on. CSP is based on whitelisting, meaning that by default everything is denied and only the specified resources can be accessed. This means that, when the rules are fine tuned, even if a malicious script is inserted into our site, it will not be executed.

内容安全策略是对抗XSS的主要武器。 该机制包含一组策略和指令,用于指定允许执行哪些脚本,可以从中加载资源,是否可以运行内联样式或脚本等。 CSP基于白名单,这意味着默认情况下所有内容都被拒绝,并且只能访问指定的资源。 这意味着,对规则进行微调后,即使将恶意脚本插入到我们的网站中,也不会执行该脚本。

Here are some resources that will help you understand this mechanism better:

以下是一些资源,可以帮助您更好地了解此机制:

HTTP / 2协议 (HTTP/2 protocol)

From the very beginning, the Web has been running on top of the HTTP protocol. Yet, while the first one had evolved tremendously, HTTP has remained mostly unchanged. In the complex ecosystem of modern websites and applications, HTTP can be a performance bottleneck. Sure, there are techniques and practices that can optimize the process, but there is only so much that can be done.

从一开始,Web就一直在HTTP协议之上运行。 然而,尽管第一个已经取得了巨大的发展,但HTTP基本上保持不变。 在现代网站和应用程序的复杂生态系统中,HTTP可能是性能瓶颈。 当然,有可以优化流程的技术和实践,但是只能做很多事情。

That’s why a second iteration of the protocol, named HTTP/2, was developed, based on Google’s SPDY protocol. It was approved on February 2015 and the specs were published as RFC 7540 in May 2016. So far the mainstream browsers support HTTP/2 only over encrypted connections and it is highly possible it will remain like this for the foreseeable future to encourage site owners to switch to HTTPS.

这就是为什么基于Google的SPDY协议开发了名为HTTP/2的协议的第二次迭代的原因。 它于2015年2月获得批准,规范于2016年5月以RFC 7540的形式发布。到目前为止,主流浏览器仅通过加密连接支持HTTP / 2,并且在可预见的将来很有可能会保持这种状态,以鼓励站点所有者切换到HTTPS。

Adoption of HTTP/2 is not a simple matter of changing some configuration settings. Some of the best practices used to enhance performance on HTTP can have an impact on the performance over HTTP/2. To find out if your website is ready for HTTP/2, you can consult the resources below:

采用HTTP / 2并不是更改某些配置设置的简单问题。 用于增强HTTP性能的一些最佳做法可能会对HTTP / 2上的性能产生影响。 要了解您的网站是否已准备好使用HTTP / 2,可以参考以下资源:

资源提示:预取 (Resource hints: Prefetching)

Web performance is all the craze nowadays and for good reason. As everyone working in the field knows, a good deal of the loading time of a page is taken by the resource download. Wouldn’t it be nice if one could use the time after a page has loaded to preload resources for the next steps? That is exactly what resource hints are for.

Web性能是当今的所有热潮,这是有充分理由的。 众所周知,在该领域工作的每个人都需要通过资源下载来加载页面。 如果可以在页面加载后使用时间为后续步骤预加载资源,那不是很好吗? 这正是资源提示的目的。

Resource hints are a series of directives that tell the browser to make available, ahead of time, specific resources that will be needed later down the road. The list contains five hints, as follows:

资源提示是一系列指令,它们告诉浏览器提前提供以后将需要的特定资源。 该列表包含五个提示,如下所示:

  • dns-prefetch

    dns预取
  • preconnect

    预连接
  • prefetch

    预取
  • preload

    预载
  • prerender

    呈现

Out of these five possible options, the only one with good browser support at this moment is prefetch. This hint tells the browser to cache documents that the user is most likely to request after the current page. This limits its use to elements that can be cached. Using it with other types of resources will not work.

在这五个可能的选项中,目前唯一具有良好浏览器支持的选项是prefetch 。 此提示告诉浏览器缓存用户最有可能在当前页面之后请求的文档。 这将它的使用限制为可以缓存的元素。 将其与其他类型的资源一起使用将不起作用。

If you are interested in this topic, here is a list of resources to provide more details:

如果您对此主题感兴趣,请使用以下资源列表,以提供更多详细信息:

严格的运输安全 (Strict Transport Security)

HTTPS is becoming the new standard for browsing and more and more websites accept only secured connections. Normal connections (on HTTP) are usually redirected to the HTTPS version and things go on as usual. However, this approach is vulnerable to a “man-in-the-middle” attack where the redirection happens instead to a spoof clone of the website you want (usually a banking site) in order to steal your login credentials.

HTTPS成为浏览的新标准,越来越多的网站仅接受安全连接。 普通连接(在HTTP上)通常被重定向到HTTPS版本,并且一切照常进行。 但是,这种方法容易受到“中间人”攻击,在这种情况下,重定向发生,而不是您想要窃取登录凭据的网站(通常是银行网站)的欺骗克隆。

This is where the Strict Transport Security header comes into play. The first time you connect to the desired website with HTTPS, the header is sent to the browser. The next time you connect, even if you use just the HTTP version of the URL, the browser will go directly to the HTTPS version, without going through the redirect cycle. As no connection is made on HTTP, the attack described earlier can’t happen.

这就是“严格传输安全性”标头起作用的地方。 第一次使用HTTPS连接到所需的网站时,标头将发送到浏览器。 下次连接时,即使仅使用URL的HTTP版本,浏览器也将直接转到HTTPS版本,而无需经历重定向周期。 由于没有在HTTP上建立连接,因此不会发生前面描述的攻击。

For more details on the Strict Transport Security header, check the following website:

有关“严格传输安全性”标头的更多详细信息,请访问以下网站:

设备像素比 (Device Pixel Ratio)

Window.devicePixelRatio is a read-only property that returns the ratio of the (vertical) size of one physical pixel on the current display device to the size of one CSS pixel. This way, developers can detect high-density screens (like Retina displays from Apple or high-end Android screens). Used together with Media Queries and MatchMedia (which we discussed above), this property allows delivery of optimized resources for the best possible experience.

Window.devicePixelRatio是一个只读属性,它返回当前显示设备上一个物理像素的(垂直)大小与一个CSS像素大小的比率。 这样,开发人员可以检测高密度的屏幕(例如Apple的Retina显示屏或高端Android屏幕)。 与媒体查询和MatchMedia(我们在上文中讨论过)一起使用时,此属性可提供优化的资源,以获得最佳体验。

网络视频文字轨道 (Web Video Text Tracks)

Web Video Text Tracks (or WebVTT) is a format for marking up text captions for multimedia resources. It is used together with the HTML5 <track> element and enables the presence of subtitles, translations, captions or descriptions to a media resource (audio or video) in a synchronized way. The presence of this textual information makes the media resource a lot more accessible.

Web视频文本轨道(或WebVTT)是一种用于标记多媒体资源文本标题的格式。 它与HTML5 <track>元素一起使用,并允许以同步方式显示对媒体资源(音频或视频)的字幕,翻译,字幕或描述。 此文本信息的存在使媒体资源更易于访问。

For instructions on how to get started with this functionality, check the following resources:

有关如何开始使用此功能的说明,请检查以下资源:

包装东西 (Wrapping Things Up)

Here we are, at the end of this series of articles that started as a simple intellectual exercise: “The oldIE is gone! Let’s party! (…hours later…) Now what?”. We covered a broad range of topics, from the techniques and practices that were no longer needed to all the new stuff that we could now do freely without polyfills, be it HTML, CSS or native JavaScript. We even touched on wider topics like performance optimization and enhancing security.

在这一系列文章的结尾,我们开始了,这只是一个简单的智力练习:“ oldIE消失了! 狂欢吧! (……几个小时后……)现在呢?”。 我们涵盖了广泛的主题,从不再需要的技术和实践,到现在无需HTML,CSS或本机JavaScript即可使用polyfills自由进行的所有新工作。 我们甚至涉及更广泛的主题,例如性能优化和增强安全性。

Should you just jump in now and start refactoring all your code? Most probably not. Such a decision must be taken depending on the balance between the cost of refactoring versus the cost of the technological debt. But if you are starting a new project, by all means, build it for the future, not for the past.

您是否应该立即进入并开始重构所有代码? 很可能不是。 必须根据重构成本与技术债务成本之间的平衡做出决定。 但是,如果您要启动一个新项目,则一定要为将来而不是过去进行构建。

翻译自: https://www.sitepoint.com/native-javascript-development-after-internet-explorer/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值