What is zone.js?
The zone.js package is a library that implements Zones for JavaScript. Zones are execution contexts that allow you to intercept and keep track of asynchronous operations in JavaScript. This is particularly useful for debugging, performance tracking, and managing multiple tasks in complex applications such as Angular.
What are zone.js's main functionalities?
Error Handling
Intercepts errors within a specific zone and allows custom error handling.
Zone.current.fork({
name: 'errorHandlingZone',
onHandleError: (parentZoneDelegate, currentZone, targetZone, error) => {
console.error('Error intercepted in zone:', error);
return false;
}
}).run(() => {
throw new Error('Test Error');
});
Execution Context Tracking
Tracks the scheduling and execution of asynchronous tasks, providing insights into the application's asynchronous flow.
Zone.current.fork({
name: 'trackingZone',
onScheduleTask: (delegate, currentZone, targetZone, task) => {
console.log('Task scheduled:', task.source);
return delegate.scheduleTask(targetZone, task);
}
}).run(() => {
setTimeout(() => {
console.log('Timeout callback executed.');
}, 1000);
});
Performance Monitoring
Measures the time taken to execute asynchronous tasks, which can be used for performance analysis.
Zone.current.fork({
name: 'performanceMonitoringZone',
onInvokeTask: (delegate, currentZone, targetZone, task, applyThis, applyArgs) => {
const start = performance.now();
delegate.invokeTask(targetZone, task, applyThis, applyArgs);
const duration = performance.now() - start;
console.log('Task took:', duration, 'ms');
}
}).run(() => {
setTimeout(() => {
console.log('Timeout callback executed.');
}, 1000);
});
Other packages similar to zone.js
async_hooks
async_hooks is a core Node.js module that provides an API to track asynchronous resources. Unlike zone.js, which works in both browser and Node.js environments, async_hooks is specific to Node.js. It offers a lower-level API compared to zone.js and requires more manual handling.
cls-hooked
cls-hooked is a Node.js package that uses async_hooks to provide continuation-local storage (CLS). It allows you to set and get context across async operations, similar to how zones work. However, cls-hooked focuses on context propagation rather than the broader range of interception capabilities that zone.js offers.
continuation-local-storage
continuation-local-storage is another Node.js package that provides CLS functionality. It predates cls-hooked and async_hooks, and it uses a different mechanism to track context. It is less performant than cls-hooked and has been largely superseded by it, but it serves a similar purpose to zone.js in terms of context management.
Zone.js
Implements Zones for JavaScript, inspired by Dart.
If you're using zone.js via unpkg (i.e. using https://unpkg.com/zone.js
)
and you're using any of the following libraries, make sure you import them first
- 'newrelic' as it patches global.Promise before zone.js does
- 'async-listener' as it patches global.setTimeout, global.setInterval before zone.js does
- 'continuation-local-storage' as it uses async-listener
NEW Zone.js POST-v0.6.0
See the new API here.
Read up on Zone Primer.
BREAKING CHANGES since Zone.js v0.11.1
Prior to v0.11.1
, Zone.js provided two distribution bundle formats in the dist
folder.
They were (1) ES5
bundle distributed as zone.js
and (2) ES2015
bundle distributed as zone-evergreen.js
.
These bundles are used for Angular's differential-loading mechanism.
Prior to v0.11.11
the following code
import 'zone.js';
would load the ES5
bundle from dist/zone.js
.
Starting with v0.11.1
, Zone.js follows the Angular Package Format, so the folder structure of the Zone.js bundles is updated to match Angular Package Format
.
So the same code
import 'zone.js';
now loads the ES2015
bundle instead.
This is a breaking change for legacy browsers such as IE11
.
For backwards compatibility zone.js
continues to distribute the same bundles under dist
.
To restore the old behavior change the polyfills.ts
generated by Angular CLI
to import like so:
import 'zone.js/dist/zone';
For details, please refer the changelog and the PR.
What's a Zone?
A Zone is an execution context that persists across async tasks.
You can think of it as thread-local storage for JavaScript VMs.
See this video from ng-conf 2014 for a detailed explanation:
See also
Standard API support
zone.js patched most standard web APIs (such as DOM events, XMLHttpRequest
, ...) and nodejs APIs
(EventEmitter
, fs
, ...), for more details, please see STANDARD-APIS.md.
Nonstandard API support
We are adding support to some nonstandard APIs, such as MediaQuery and
Notification. Please see NON-STANDARD-APIS.md for more details.
Examples
You can find some samples to describe how to use zone.js in SAMPLE.md.
Modules
zone.js patches the async APIs described above, but those patches will have some overhead.
Starting from zone.js v0.8.9, you can choose which web API module you want to patch.
For more details, please
see MODULE.md.
Bundles
Starting with v0.11.0
, zone.js
uses Angular Package Format
for bundle distribution.
(For backwards compatibility, all bundles can still be accessed from dist
folder.)
Bundle | Summary |
---|
zone.js | The default bundle. Contains the most used APIs such as setTimeout/Promise/EventTarget... , it also supports differential loading by importing this bundle using import zone.js . In legacy browsers it includes some additional patches such as registerElement and EventTarget like APIs. |
zone-testing.js | The bundle for zone testing support of jasmine / mocha / jest . Also includes test utility functions async / fakeAsync / sync . |
zone-node.js | The NodeJS support bundle. |
zone-mix.js | A mixed bundle which supports both browser and NodeJS. Useful for mixed environment such as Electron. |
zone-externs.js | the API definitions for closure compiler . |
Additional optional patches not included in the zone.js
bundles which extend functionality.
The additional bundles can be found under zone.js/plugins
folder.
To use these bundles, add the following code after importing zone.js bundle.
import 'zone.js';
// For example, import canvas patch
import 'zone.js/plugins/zone-patch-canvas';
Patch | Summary |
---|
webapis-media-query.js | patch for MediaQuery APIs |
webapis-notification.js | patch for Notification APIs |
webapis-rtc-peer-connection.js | patch for RTCPeerConnection APIs |
webapis-shadydom.js | patch for Shady DOM APIs |
zone-bluebird.js | patch for Bluebird APIs |
zone-error.js | patch for Error Global Object , supports adding zone information to stack frame, and also removing unrelated stack frames from zone.js internally |
zone-patch-canvas.js | patch for Canvas API |
zone-patch-cordova.js | patch for Cordova API |
zone-patch-electron.js | patch for Electron API |
zone-patch-fetch.js | patch for Fetch API |
zone-patch-jsonp.js | helper utility for jsonp API |
zone-patch-resize-observer.js | patch for ResizeObserver API |
zone-patch-rxjs.js | patch for rxjs API |
zone-patch-rxjs-fake-async.js | patch for rxjs fakeasync test |
zone-patch-socket-io.js | patch for socket-io |
zone-patch-user-media.js | patch for UserMedia API |
zone-patch-message-port.js | patch for MessagePort API |
Promise A+ test passed
License
MIT