Another abandoned server code base... this is kind of an ancestor of taskrambler.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

1983 lines
117 KiB

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"><html lang="en-US-x-Hixie"><title>Web Workers</title><style type="text/css">
pre { margin-left: 2em; white-space: pre-wrap; }
h2 { margin: 3em 0 1em 0; }
h3 { margin: 2.5em 0 1em 0; }
h4 { margin: 2.5em 0 0.75em 0; }
h5, h6 { margin: 2.5em 0 1em; }
h1 + h2, h1 + h2 + h2 { margin: 0.75em 0 0.75em; }
h2 + h3, h3 + h4, h4 + h5, h5 + h6 { margin-top: 0.5em; }
p { margin: 1em 0; }
hr:not(.top) { display: block; background: none; border: none; padding: 0; margin: 2em 0; height: auto; }
dl, dd { margin-top: 0; margin-bottom: 0; }
dt { margin-top: 0.75em; margin-bottom: 0.25em; clear: left; }
dt + dt { margin-top: 0; }
dd dt { margin-top: 0.25em; margin-bottom: 0; }
dd p { margin-top: 0; }
dd dl + p { margin-top: 1em; }
dd table + p { margin-top: 1em; }
p + * > li, dd li { margin: 1em 0; }
dt, dfn { font-weight: bold; font-style: normal; }
i, em { font-style: italic; }
dt dfn { font-style: italic; }
pre, code { font-size: inherit; font-family: monospace; font-variant: normal; }
pre strong { color: black; font: inherit; font-weight: bold; background: yellow; }
pre em { font-weight: bolder; font-style: normal; }
@media screen { code { color: orangered; } code :link, code :visited { color: inherit; } }
var sub { vertical-align: bottom; font-size: smaller; position: relative; top: 0.1em; }
table { border-collapse: collapse; border-style: hidden hidden none hidden; }
table thead, table tbody { border-bottom: solid; }
table tbody th:first-child { border-left: solid; }
table tbody th { text-align: left; }
table td, table th { border-left: solid; border-right: solid; border-bottom: solid thin; vertical-align: top; padding: 0.2em; }
blockquote { margin: 0 0 0 2em; border: 0; padding: 0; font-style: italic; }
.bad, .bad *:not(.XXX) { color: gray; border-color: gray; background: transparent; }
.matrix, .matrix td { border: none; text-align: right; }
.matrix { margin-left: 2em; }
.dice-example { border-collapse: collapse; border-style: hidden solid solid hidden; border-width: thin; margin-left: 3em; }
.dice-example caption { width: 30em; font-size: smaller; font-style: italic; padding: 0.75em 0; text-align: left; }
.dice-example td, .dice-example th { border: solid thin; width: 1.35em; height: 1.05em; text-align: center; padding: 0; }
.toc dfn, h1 dfn, h2 dfn, h3 dfn, h4 dfn, h5 dfn, h6 dfn { font: inherit; }
img.extra, p.overview { float: right; }
pre.idl { border: solid thin; background: #EEEEEE; color: black; padding: 0.5em 1em; position: relative; }
pre.idl :link, pre.idl :visited { color: inherit; background: transparent; }
pre.idl::before { content: "IDL"; font: bold small sans-serif; padding: 0.5em; background: white; position: absolute; top: 0; margin: -1px 0 0 -4em; width: 1.5em; border: thin solid; border-radius: 0 0 0 0.5em }
pre.css { border: solid thin; background: #FFFFEE; color: black; padding: 0.5em 1em; }
pre.css:first-line { color: #AAAA50; }
dl.domintro { color: green; margin: 2em 0 2em 2em; padding: 0.5em 1em; border: none; background: #DDFFDD; }
hr + dl.domintro, div.impl + dl.domintro { margin-top: 2.5em; margin-bottom: 1.5em; }
dl.domintro dt, dl.domintro dt * { color: black; text-decoration: none; }
dl.domintro dd { margin: 0.5em 0 1em 2em; padding: 0; }
dl.domintro dd p { margin: 0.5em 0; }
dl.switch { padding-left: 2em; }
dl.switch > dt { text-indent: -1.5em; }
dl.switch > dt:before { content: '\21AA'; padding: 0 0.5em 0 0; display: inline-block; width: 1em; text-align: right; line-height: 0.5em; }
dl.triple { padding: 0 0 0 1em; }
dl.triple dt, dl.triple dd { margin: 0; display: inline }
dl.triple dt:after { content: ':'; }
dl.triple dd:after { content: '\A'; white-space: pre; }
.diff-old { text-decoration: line-through; color: silver; background: transparent; }
.diff-chg, .diff-new { text-decoration: underline; color: green; background: transparent; }
a .diff-new { border-bottom: 1px blue solid; }
h2 { page-break-before: always; }
h1, h2, h3, h4, h5, h6 { page-break-after: avoid; }
h1 + h2, hr + h2.no-toc { page-break-before: auto; }
p > span:not([title=""]):not([class="XXX"]):not([class="impl"]):not([class="note"]),
li > span:not([title=""]):not([class="XXX"]):not([class="impl"]):not([class="note"]), { border-bottom: solid #9999CC; }
div.head { margin: 0 0 1em; padding: 1em 0 0 0; }
div.head p { margin: 0; }
div.head h1 { margin: 0; }
div.head .logo { float: right; margin: 0 1em; }
div.head .logo img { border: none } /* remove border from top image */
div.head dl { margin: 1em 0; }
div.head p.copyright, div.head p.alt { font-size: x-small; font-style: oblique; margin: 0; }
body > .toc > li { margin-top: 1em; margin-bottom: 1em; }
body > .toc.brief > li { margin-top: 0.35em; margin-bottom: 0.35em; }
body > .toc > li > * { margin-bottom: 0.5em; }
body > .toc > li > * > li > * { margin-bottom: 0.25em; }
.toc, .toc li { list-style: none; }
.brief { margin-top: 1em; margin-bottom: 1em; line-height: 1.1; }
.brief li { margin: 0; padding: 0; }
.brief li p { margin: 0; padding: 0; }
.category-list { margin-top: -0.75em; margin-bottom: 1em; line-height: 1.5; }
.category-list::before { content: '\21D2\A0'; font-size: 1.2em; font-weight: 900; }
.category-list li { display: inline; }
.category-list li:not(:last-child)::after { content: ', '; }
.category-list li > span, .category-list li > a { text-transform: lowercase; }
.category-list li * { text-transform: none; } /* don't affect <code> nested in <a> */
.XXX { color: #E50000; background: white; border: solid red; padding: 0.5em; margin: 1em 0; }
.XXX > :first-child { margin-top: 0; }
p .XXX { line-height: 3em; }
.annotation { border: solid thin black; background: #0C479D; color: white; position: relative; margin: 8px 0 20px 0; }
.annotation:before { position: absolute; left: 0; top: 0; width: 100%; height: 100%; margin: 6px -6px -6px 6px; background: #333333; z-index: -1; content: ''; }
.annotation :link, .annotation :visited { color: inherit; }
.annotation :link:hover, .annotation :visited:hover { background: transparent; }
.annotation span { border: none ! important; }
.note { color: green; background: transparent; font-family: sans-serif; }
.warning { color: red; background: transparent; }
.note, .warning { font-weight: bolder; font-style: italic; }
.note em, .warning em, .note i, .warning i { font-style: normal; }
p.note, div.note { padding: 0.5em 2em; }
span.note { padding: 0 2em; }
.note p:first-child, .warning p:first-child { margin-top: 0; }
.note p:last-child, .warning p:last-child { margin-bottom: 0; }
.warning:before { font-style: normal; }
p.note:before { content: 'Note: '; }
p.warning:before { content: '\26A0 Warning! '; }
.bookkeeping:before { display: block; content: 'Bookkeeping details'; font-weight: bolder; font-style: italic; }
.bookkeeping { font-size: 0.8em; margin: 2em 0; }
.bookkeeping p { margin: 0.5em 2em; display: list-item; list-style: square; }
.bookkeeping dt { margin: 0.5em 2em 0; }
.bookkeeping dd { margin: 0 3em 0.5em; }
h4 { position: relative; z-index: 3; }
h4 + .element, h4 + div + .element { margin-top: -2.5em; padding-top: 2em; }
.element {
background: #EEEEFF;
color: black;
margin: 0 0 1em 0.15em;
padding: 0 1em 0.25em 0.75em;
border-left: solid #9999FF 0.25em;
position: relative;
z-index: 1;
}
.element:before {
position: absolute;
z-index: 2;
top: 0;
left: -1.15em;
height: 2em;
width: 0.9em;
background: #EEEEFF;
content: ' ';
border-style: none none solid solid;
border-color: #9999FF;
border-width: 0.25em;
}
.example { display: block; color: #222222; background: #FCFCFC; border-left: double; margin-left: 2em; padding-left: 1em; }
td > .example:only-child { margin: 0 0 0 0.1em; }
ul.domTree, ul.domTree ul { padding: 0 0 0 1em; margin: 0; }
ul.domTree li { padding: 0; margin: 0; list-style: none; position: relative; }
ul.domTree li li { list-style: none; }
ul.domTree li:first-child::before { position: absolute; top: 0; height: 0.6em; left: -0.75em; width: 0.5em; border-style: none none solid solid; content: ''; border-width: 0.1em; }
ul.domTree li:not(:last-child)::after { position: absolute; top: 0; bottom: -0.6em; left: -0.75em; width: 0.5em; border-style: none none solid solid; content: ''; border-width: 0.1em; }
ul.domTree span { font-style: italic; font-family: serif; }
ul.domTree .t1 code { color: purple; font-weight: bold; }
ul.domTree .t2 { font-style: normal; font-family: monospace; }
ul.domTree .t2 .name { color: black; font-weight: bold; }
ul.domTree .t2 .value { color: blue; font-weight: normal; }
ul.domTree .t3 code, .domTree .t4 code, .domTree .t5 code { color: gray; }
ul.domTree .t7 code, .domTree .t8 code { color: green; }
ul.domTree .t10 code { color: teal; }
body.dfnEnabled dfn { cursor: pointer; }
.dfnPanel {
display: inline;
position: absolute;
z-index: 10;
height: auto;
width: auto;
padding: 0.5em 0.75em;
font: small sans-serif, Droid Sans Fallback;
background: #DDDDDD;
color: black;
border: outset 0.2em;
}
.dfnPanel * { margin: 0; padding: 0; font: inherit; text-indent: 0; }
.dfnPanel :link, .dfnPanel :visited { color: black; }
.dfnPanel p { font-weight: bolder; }
.dfnPanel * + p { margin-top: 0.25em; }
.dfnPanel li { list-style-position: inside; }
#configUI { position: absolute; z-index: 20; top: 10em; right: 1em; width: 11em; font-size: small; }
#configUI p { margin: 0.5em 0; padding: 0.3em; background: #EEEEEE; color: black; border: inset thin; }
#configUI p label { display: block; }
#configUI #updateUI, #configUI .loginUI { text-align: center; }
#configUI input[type=button] { display: block; margin: auto; }
fieldset { margin: 1em; padding: 0.5em 1em; }
fieldset > legend + * { margin-top: 0; }
fieldset > :last-child { margin-bottom: 0; }
fieldset p { margin: 0.5em 0; }
</style><link href="http://www.w3.org/StyleSheets/TR/W3C-WD" rel="stylesheet" type="text/css"><script type="text/javascript">
function getCookie(name) {
var params = location.search.substr(1).split("&");
for (var index = 0; index < params.length; index++) {
if (params[index] == name)
return "1";
var data = params[index].split("=");
if (data[0] == name)
return unescape(data[1]);
}
var cookies = document.cookie.split("; ");
for (var index = 0; index < cookies.length; index++) {
var data = cookies[index].split("=");
if (data[0] == name)
return unescape(data[1]);
}
return null;
}
</script><div class="head" id="head">
<p><a href="http://www.w3.org/"><img alt="W3C" height="48" src="http://www.w3.org/Icons/w3c_home" width="72"></a></p>
<h1>Web Workers</h1>
<h2 class="no-num no-toc" id="lcwd-01-september-2011">W3C Working Draft 01 September 2011</h2>
<dl>
<dt>This Version:</dt>
<dd><a href="http://www.w3.org/TR/2011/WD-workers-20110901/">http://www.w3.org/TR/2011/WD-workers-20110901/</a></dd>
<dt>Latest Published Version:</dt>
<dd><a href="http://www.w3.org/TR/workers/">http://www.w3.org/TR/workers/</a></dd>
<dt>Latest Editor's Draft:</dt>
<dd><a class="latest-link" href="http://dev.w3.org/html5/workers/">http://dev.w3.org/html5/workers/</a></dd>
<dt>Previous Versions:</dt>
<dd><a href="http://www.w3.org/TR/2011/WD-workers-20110310/">http://www.w3.org/TR/2011/WD-workers-20110310/</a></dd>
<dd><a href="http://www.w3.org/TR/2011/WD-workers-20110208/">http://www.w3.org/TR/2011/WD-workers-20110208/</a></dd>
<dd><a href="http://www.w3.org/TR/2009/WD-workers-20091029/">http://www.w3.org/TR/2009/WD-workers-20091029/</a></dd>
<dd><a href="http://www.w3.org/TR/2009/WD-workers-20090423/">http://www.w3.org/TR/2009/WD-workers-20090423/</a></dd>
<!-- :ZZZ -->
<dt>Editor:</dt>
<dd><a href="mailto:ian@hixie.ch">Ian Hickson</a>, Google, Inc.</dd>
</dl><p class="copyright"><a href="http://www.w3.org/Consortium/Legal/ipr-notice#Copyright">Copyright</a>
&copy; 2011 <a href="http://www.w3.org/"><abbr title="World Wide
Web Consortium">W3C</abbr></a><sup>&reg;</sup> (<a href="http://www.csail.mit.edu/"><abbr title="Massachusetts
Institute of Technology">MIT</abbr></a>, <a href="http://www.ercim.eu/"><abbr title="European Research
Consortium for Informatics and Mathematics">ERCIM</abbr></a>, <a href="http://www.keio.ac.jp/">Keio</a>), All Rights Reserved. W3C
<a href="http://www.w3.org/Consortium/Legal/ipr-notice#Legal_Disclaimer">liability</a>,
<a href="http://www.w3.org/Consortium/Legal/ipr-notice#W3C_Trademarks">trademark</a>
and <a href="http://www.w3.org/Consortium/Legal/copyright-documents">document
use</a> rules apply.</p>
<!-- UNDER NO CIRCUMSTANCES IS THE FOLLOWING PARAGRAPH TO BE REMOVED OR EDITED WITHOUT TALKING TO IAN FIRST -->
<p class="alt">The bulk of the text of this specification is also
available in the WHATWG <a href="http://www.whatwg.org/specs/web-apps/current-work/complete.html#workers">Web Applications 1.0</a> specification, under a license that permits
reuse of the specification text.</p>
<!-- UNDER NO CIRCUMSTANCES IS THE PRECEDING PARAGRAPH TO BE REMOVED OR EDITED WITHOUT TALKING TO IAN FIRST -->
</div><hr class="top"><h2 class="no-num no-toc" id="abstract">Abstract</h2><p>This specification defines an API that allows Web application
authors to spawn background workers running scripts in parallel to
their main page. This allows for thread-like operation with
message-passing as the coordination mechanism.<h2 class="no-num no-toc" id="status-of-this-document">Status of This document</h2><p><em>This section describes the status of this document at the
time of its publication. Other documents may supersede this
document. A list of current W3C publications and the
most recently formally published <!-- DO NOT CHANGE THIS BACK TO THE STANDARD BOILERPLATE, AS IT IS INACCURATE -->
revision of this technical report can be found in the <a href="http://www.w3.org/TR/">W3C technical reports index</a> at
http://www.w3.org/TR/.</em></p><p>If you wish to make comments regarding this document in a manner
that is tracked by the W3C, please submit them via using <a href="http://www.w3.org/Bugs/Public/enter_bug.cgi?product=HTML%20WG">our
public bug database</a>. If you do not have an account then you can
enter feedback using this form:<form action="http://www.whatwg.org/specs/web-apps/current-work/file-spam.cgi" method="post">
<fieldset><legend>Feedback Comments</legend>
<input name="id" type="hidden" value="top"><input name="component" type="hidden" value="Web Workers (editor: Ian Hickson)"><input name="response" type="hidden" value="html"><p><label for="feedbackBox">Please enter your feedback, carefully
indicating the title of the section for which you are submitting
feedback, quoting the text that's wrong today if appropriate. If
you're suggesting a new feature, it's really important to say
<em>what</em> the problem you're trying to solve is. That's more
important than the solution, in fact.</label></p>
<p><textarea cols="79" id="feedbackBox" name="text" rows="10"></textarea></p>
<p class="note">Please don't use section numbers as these tend to
change rapidly and make your feedback harder to understand.</p>
<script type="text/javascript">
function checkFeedbackForm(form) {
if (form.elements.text.value.match(/^ *</)) {
alert('Please don\'t start your feedback with an angle bracket, instead explain what topic your feedback is about first.');
return true;
} else if (form.elements.text.value.match(/ [^ ]+ [^ ]+ [^ ]+ [^ ]+ /)) {
if (form.elements.text.value.match(/^Please enter your feedback, carefully/)) {
alert('Please enter your feedback, explaining what is wrong, and without repeating the instructions. Thanks!');
return true;
} else if (form.elements.text.value.match(/ [^ ]+ [^ ]+ [^ ]+ [^ ]+ /)) {
form.action = "http://www.whatwg.org/specs/web-apps/current-work/file-bug.cgi";
return true;
} else {
alert('Please include significantly more detail about exactly what problem you are trying to solve.');
return false;
}
}
}
</script><p>
<input onclick="return checkFeedbackForm(form)" type="submit" value="Submit feedback"><small>(Note: Your IP address and user agent will be publicly recorded for spam prevention purposes.)</small>
</p>
</fieldset></form><p>You can also e-mail feedback to <a href="mailto:public-webapps@w3.org">public-webapps@w3.org</a> (<a href="mailto:public-webapps-request@w3.org?subject=subscribe">subscribe</a>,
<a href="http://lists.w3.org/Archives/Public/public-webapps/">archives</a>),
or <a href="mailto:whatwg@whatwg.org">whatwg@whatwg.org</a> (<a href="http://lists.whatwg.org/listinfo.cgi/whatwg-whatwg.org">subscribe</a>,
<a href="http://lists.whatwg.org/pipermail/whatwg-whatwg.org/">archives</a>).
All feedback is welcome.</p><p><strong>Implementors who are not taking part in the
discussions are likely to find the specification changing out from
under them in incompatible ways.</strong> Vendors interested in
implementing this specification before it eventually reaches the
Candidate Recommendation stage should join the aforementioned
mailing lists and take part in the discussions.<div id="multipage-common">
</div><p>The latest
stable version of the editor's draft of this specification is always
available on <a href="http://dev.w3.org/html5/workers/">the W3C CVS server</a>
and in the <a href="http://svn.whatwg.org/webapps/">WHATWG
Subversion repository</a>. The <a href="http://www.whatwg.org/specs/web-apps/current-work/complete.html">latest
editor's working copy</a> (which may contain unfinished text in the
process of being prepared) contains the latest draft text of this
specification (amongst others). For more details, please see the <a href="http://wiki.whatwg.org/wiki/FAQ#What_are_the_various_versions_of_the_spec.3F">WHATWG
FAQ</a>.<p>Notifications of changes to this specification are sent along
with notifications of changes to related specifications using the
following mechanisms:<dl><dt>E-mail notifications of changes</dt>
<dd>Commit-Watchers mailing list (complete source diffs): <a href="http://lists.whatwg.org/listinfo.cgi/commit-watchers-whatwg.org">http://lists.whatwg.org/listinfo.cgi/commit-watchers-whatwg.org</a></dd>
<dt>Browsable version-control record of all changes:</dt>
<dd>CVSWeb interface with side-by-side diffs: <a href="http://dev.w3.org/cvsweb/html5/">http://dev.w3.org/cvsweb/html5/</a></dd>
<dd>Annotated summary with unified diffs: <a href="http://html5.org/tools/web-apps-tracker">http://html5.org/tools/web-apps-tracker</a></dd>
<dd>Raw Subversion interface: <code>svn checkout http://svn.whatwg.org/webapps/</code></dd>
</dl><p>The W3C <a href="http://www.w3.org/2008/webapps/">Web Applications
Working Group</a> is the W3C working group responsible for this
specification's progress along the W3C Recommendation track.
This specification is the 01 September 2011 Last Call Working Draft. The Last Call review period will end on 27 September 2011.
</p><p>This document was produced by a group operating under the <a href="http://www.w3.org/Consortium/Patent-Policy-20040205/">5
February 2004 W3C Patent Policy</a>. W3C maintains a <a href="http://www.w3.org/2004/01/pp-impl/42538/status" rel="disclosure">public list of
any patent disclosures</a> made in connection with the deliverables
of the group; that page also includes instructions for disclosing a
patent. An individual who has actual knowledge of a patent which the
individual believes contains <a href="http://www.w3.org/Consortium/Patent-Policy-20040205/#def-essential">Essential
Claim(s)</a> must disclose the information in accordance with <a href="http://www.w3.org/Consortium/Patent-Policy-20040205/#sec-Disclosure">section
6 of the W3C Patent Policy</a>.<h2 class="no-num no-toc" id="contents">Table of Contents</h2>
<ol class="toc">
<li><a href="#introduction"><span class="secno">1 </span>Introduction</a>
<ol>
<li><a href="#scope"><span class="secno">1.1 </span>Scope</a></li>
<li><a href="#examples"><span class="secno">1.2 </span>Examples</a>
<ol>
<li><a href="#a-background-number-crunching-worker"><span class="secno">1.2.1 </span>A background number-crunching worker</a></li>
<li><a href="#a-worker-for-updating-a-client-side-database"><span class="secno">1.2.2 </span>A worker for updating a client-side database</a></li>
<li><a href="#worker-used-for-background-i-o"><span class="secno">1.2.3 </span>Worker used for background I/O</a></li>
<li><a href="#shared-workers-introduction"><span class="secno">1.2.4 </span>Shared workers introduction</a></li>
<li><a href="#shared-state-using-a-shared-worker"><span class="secno">1.2.5 </span>Shared state using a shared worker</a></li>
<li><a href="#delegation"><span class="secno">1.2.6 </span>Delegation</a></ol></li>
<li><a href="#tutorials"><span class="secno">1.3 </span>Tutorials</a>
<ol>
<li><a href="#creating-a-dedicated-worker"><span class="secno">1.3.1 </span>Creating a dedicated worker</a></li>
<li><a href="#communicating-with-a-dedicated-worker"><span class="secno">1.3.2 </span>Communicating with a dedicated worker</a></li>
<li><a href="#shared-workers"><span class="secno">1.3.3 </span>Shared workers</a></ol></ol></li>
<li><a href="#conformance-requirements"><span class="secno">2 </span>Conformance requirements</a>
<ol>
<li><a href="#dependencies"><span class="secno">2.1 </span>Dependencies</a></ol></li>
<li><a href="#terminology"><span class="secno">3 </span>Terminology</a></li>
<li><a href="#infrastructure"><span class="secno">4 </span>Infrastructure</a>
<ol>
<li><a href="#dependencies-0"><span class="secno">4.1 </span>Dependencies</a></li>
<li><a href="#the-global-scope"><span class="secno">4.2 </span>The global scope</a>
<ol>
<li><a href="#the-workerglobalscope-abstract-interface"><span class="secno">4.2.1 </span>The <code>WorkerGlobalScope</code> abstract interface</a></li>
<li><a href="#dedicated-workers-and-the-dedicatedworkerglobalscope-interface"><span class="secno">4.2.2 </span>Dedicated workers and the <code>DedicatedWorkerGlobalScope</code> interface</a></li>
<li><a href="#shared-workers-and-the-sharedworkerglobalscope-interface"><span class="secno">4.2.3 </span>Shared workers and the <code>SharedWorkerGlobalScope</code> interface</a></ol></li>
<li><a href="#origins-of-workers"><span class="secno">4.3 </span>Origins of workers</a></li>
<li><a href="#the-event-loop"><span class="secno">4.4 </span>The event loop</a></li>
<li><a href="#the-worker-s-lifetime"><span class="secno">4.5 </span>The worker's lifetime</a></li>
<li><a href="#processing-model"><span class="secno">4.6 </span>Processing model</a></li>
<li><a href="#runtime-script-errors"><span class="secno">4.7 </span>Runtime script errors</a></li>
<li><a href="#creating-workers"><span class="secno">4.8 </span>Creating workers</a>
<ol>
<li><a href="#the-abstractworker-abstract-interface"><span class="secno">4.8.1 </span>The <code>AbstractWorker</code> abstract interface</a></li>
<li><a href="#dedicated-workers-and-the-worker-interface"><span class="secno">4.8.2 </span>Dedicated workers and the <code>Worker</code> interface</a></li>
<li><a href="#shared-workers-and-the-sharedworker-interface"><span class="secno">4.8.3 </span>Shared workers and the <code>SharedWorker</code> interface</a></ol></ol></li>
<li><a href="#apis-available-to-workers"><span class="secno">5 </span>APIs available to workers</a>
<ol>
<li><a href="#importing-scripts-and-libraries"><span class="secno">5.1 </span>Importing scripts and libraries</a></li>
<li><a href="#the-workernavigator-object"><span class="secno">5.2 </span>The <code>WorkerNavigator</code> object</a></li>
<li><a href="#interface-objects-and-constructors"><span class="secno">5.3 </span>Interface objects and constructors</a></li>
<li><a href="#worker-locations"><span class="secno">5.4 </span>Worker locations</a></ol></li>
<li><a class="no-num" href="#references">References</a></li>
<li><a class="no-num" href="#acknowledgements">Acknowledgements</a></ol>
<hr><h2 id="introduction"><span class="secno">1 </span>Introduction</h2><h3 id="scope"><span class="secno">1.1 </span>Scope</h3><p><i>This section is non-normative.</i><p>This specification defines an API for running scripts in the
background independently of any user interface scripts.<p>This allows for long-running scripts that are not interrupted by
scripts that respond to clicks or other user interactions, and
allows long tasks to be executed without yielding to keep the page
responsive.<p>Workers (as these background scripts are called herein) 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 image. The examples below show
some appropriate uses of workers.<p>Generally, workers are expected to be long-lived, have a high
start-up performance cost, and a high per-instance memory cost.<h3 id="examples"><span class="secno">1.2 </span>Examples</h3><p><i>This section is non-normative.</i><p>There are a variety of uses that workers can be put to. The
following subsections show various examples of this use.<h4 id="a-background-number-crunching-worker"><span class="secno">1.2.1 </span>A background number-crunching worker</h4><p><i>This section is non-normative.</i><p>The simplest use of workers is for performing a computationally
expensive task without interrupting the user interface.<p>In this example, the main document spawns a worker to
(na&iuml;vely) compute prime numbers, and progressively displays the
most recently found prime number.<p>The main page is as follows:<pre>&lt;!DOCTYPE HTML&gt;
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;Worker example: One-core computation&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;p&gt;The highest prime number discovered so far is: &lt;output id="result"&gt;&lt;/output&gt;&lt;/p&gt;
&lt;script&gt;
var worker = new Worker('worker.js');
worker.onmessage = function (event) {
document.getElementById('result').textContent = event.data;
};
&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;</pre><p>The <code title="dom-Worker"><a href="#dom-worker">Worker()</a></code> constructor call
creates a worker and returns a <code><a href="#worker">Worker</a></code> object
representing that worker, which is used to communicate with the
worker. That object's <code title="handler-Worker-onmessage"><a href="#handler-worker-onmessage">onmessage</a></code> event handler allows the code to receive messages from the worker.<p>The worker itself is as follows:<pre>var n = 1;
search: while (true) {
n += 1;
for (var i = 2; i &lt;= Math.sqrt(n); i += 1)
if (n % i == 0)
continue search;
// found a prime!
postMessage(n);
}</pre><p>The bulk of this code is simply an unoptimized search for a prime
number. The <code title="dom-DedicatedWorkerGlobalScope-postMessage"><a href="#dom-dedicatedworkerglobalscope-postmessage">postMessage()</a></code>
method is used to send a message back to the page when a prime is
found.<p><a href="http://www.whatwg.org/demos/workers/primes/page.html">View this example online</a>.<h4 id="a-worker-for-updating-a-client-side-database"><span class="secno">1.2.2 </span>A worker for updating a client-side database</h4><p><i>This section is non-normative.</i><p>In this example, the main document spawns a worker whose only
task is to listen for notifications from the server, and, when
appropriate, either add or remove data from the client-side
database.<p>Since no communication occurs between the worker and the main
page, the main page can start the worker by just doing:<pre>&lt;script&gt;
new Worker('worker.js');
&lt;/script&gt;</pre><p>The worker itself is as follows:<pre>var server = new WebSocket('ws://whatwg.org/database');
var database = openDatabase('demobase', '1.0', 'Demo Database', 10240);
server.onmessage = function (event) {
// data is in the format "command key value"
var data = event.data.split(' ');
switch (data[0]) {
case '+':
database.transaction(function(tx) {
tx.executeSql('INSERT INTO pairs (key, value) VALUES (?, ?)', data[1], data[2]);
});
case '-':
database.transaction(function(tx) {
tx.executeSql('DELETE FROM pairs WHERE key=? AND value=?', data[1], data[2]);
});
}
};</pre><p>This connects to the server using the <code>WebSocket</code>
mechanism and opens the local database (which, we presume, has been
created earlier). The worker then just listens for messages from the
server and acts on them as appropriate, forever (or until the main
page is closed).<p><a href="http://www.whatwg.org/demos/workers/database-updater/page.html">View
this example online</a>. (This example will not actually function,
since the server does not actually exist and the database is not
created by this sample code.)<h4 id="worker-used-for-background-i-o"><span class="secno">1.2.3 </span>Worker used for background I/O</h4><p><i>This section is non-normative.</i><p>In this example, the main document uses two workers, one for
fetching stock updates for at regular intervals, and one for
fetching performing search queries that the user requests.<p>The main page is as follows:<pre>&lt;!DOCTYPE HTML&gt;
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;Worker example: Stock ticker&lt;/title&gt;
&lt;script&gt;
// TICKER
var symbol = 'GOOG'; // default symbol to watch
var ticker = new Worker('ticker.js');
// SEARCHER
var searcher = new Worker('searcher.js');
function search(query) {
searcher.postMessage(query);
}
// SYMBOL SELECTION UI
function select(newSymbol) {
symbol = newSymbol;
ticker.postMessage(symbol);
}
&lt;/script&gt;
&lt;/head&gt;
&lt;body onload="search('')"&gt;
&lt;p&gt;&lt;output id="symbol"&gt;&lt;/output&gt; &lt;output id="value"&gt;&lt;/output&gt;&lt;/p&gt;
&lt;script&gt;
ticker.onmessage = function (event) {
var data = event.data.split(' ');
document.getElementById('symbol').textContent = data[0];
document.getElementById('value').textContent = data[1];
};
ticker.postMessage(symbol);
&lt;/script&gt;
&lt;p&gt;&lt;label&gt;Search: &lt;input type="text" autofocus oninput="search(this.value)"&gt;&lt;/label&gt;&lt;/p&gt;
&lt;ul id="results"&gt;&lt;/ul&gt;
&lt;script&gt;
searcher.onmessage = function (event) {
var data = event.data.split(' ');
var results = document.getElementById('results');
while (results.hasChildNodes()) // clear previous results
results.removeChild(results.firstChild);
for (var i = 0; i &lt; data.length; i += 1) {
// add a list item with a button for each result
var li = document.createElement('li');
var button = document.createElement('button');
button.value = data[i];
button.type = 'button';
button.onclick = function () { select(this.value); };
button.textContent = data[i];
li.appendChild(button);
results.appendChild(li);
}
};
&lt;/script&gt;
&lt;p&gt;(The data in this example is not real. Try searching for "Google" or "Apple".)&lt;/p&gt;
&lt;/body&gt;
&lt;/html&gt;</pre><p>The two workers use a common library for performing the actual
network calls. This library is as follows:<pre>function get(url) {
try {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, false);
xhr.send();
return xhr.responseText;
} catch (e) {
return ''; // turn all errors into empty results
}
}</pre><p>The stock updater worker is as follows:<pre>importScripts('io.js');
var timer;
var symbol;
function update() {
postMessage(symbol + ' ' + get('stock.cgi?' + symbol));
timer = setTimeout(update, 10000);
}
onmessage = function (event) {
if (timer)
clearTimeout(timer);
symbol = event.data;
update();
};</pre><p>The search query worker is as follows:<pre>importScripts('io.js');
onmessage = function (event) {
postMessage(get('search.cgi?' + event.data));
};</pre><p><a href="http://www.whatwg.org/demos/workers/stocks/page.html">View this example online</a>.<h4 id="shared-workers-introduction"><span class="secno">1.2.4 </span>Shared workers introduction</h4><p><i>This section is non-normative.</i><p>This section introduces shared workers using a Hello World
example. Shared workers use slightly different APIs, since each
worker can have multiple connections.<p>This first example shows how you connect to a worker and how a
worker can send a message back to the page when it connects to
it. Received messages are displayed in a log.<p>Here is the HTML page:<pre>&lt;!DOCTYPE HTML&gt;
&lt;title&gt;Shared workers: demo 1&lt;/title&gt;
&lt;pre id="log"&gt;Log:&lt;/pre&gt;
&lt;script&gt;
var worker = new SharedWorker('test.js');
var log = document.getElementById('log');
worker.port.onmessage = function(e) { // note: not worker.onmessage!
log.textContent += '\n' + e.data;
}
&lt;/script&gt;
</pre><p>Here is the JavaScript worker:<pre>onconnect = function(e) {
var port = e.ports[0];
port.postMessage('Hello World!');
}
</pre><p><a href="http://www.whatwg.org/demos/workers/shared/001/test.html">View this example online</a>.<hr><p>This second example extends the first one by changing two things:
first, messages are received using <code title="">addEventListener()</code> instead of an <span title="event
handler IDL attributes">event handler IDL attribute</span>, and
second, a message is sent <em>to</em> the worker, causing the worker
to send another message in return. Received messages are again
displayed in a log.<p>Here is the HTML page:<pre>&lt;!DOCTYPE HTML&gt;
&lt;title&gt;Shared workers: demo 2&lt;/title&gt;
&lt;pre id="log"&gt;Log:&lt;/pre&gt;
&lt;script&gt;
var worker = new SharedWorker('test.js');
var log = document.getElementById('log');
worker.port.addEventListener('message', function(e) {
log.textContent += '\n' + e.data;
}, false);
worker.port.start(); // note: need this when using addEventListener
worker.port.postMessage('ping');
&lt;/script&gt;
</pre><p>Here is the JavaScript worker:<pre>onconnect = function(e) {
var port = e.ports[0];
port.postMessage('Hello World!');
port.onmessage = function(e) {
port.postMessage('pong'); // not e.ports[0].postMessage!
// e.target.postMessage('pong'); would work also
}
}
</pre><p><a href="http://www.whatwg.org/demos/workers/shared/002/test.html">View this example online</a>.<hr><p>Finally, the example is extended to show how two pages can
connect to the same worker; in this case, the second page is merely
in an <code>iframe</code> on the first page, but the same principle
would apply to an entirely separate page in a separate
<span>top-level browsing context</span>.<p>Here is the outer HTML page:<pre>&lt;!DOCTYPE HTML&gt;
&lt;title&gt;Shared workers: demo 3&lt;/title&gt;
&lt;pre id="log"&gt;Log:&lt;/pre&gt;
&lt;script&gt;
var worker = new SharedWorker('test.js');
var log = document.getElementById('log');
worker.port.addEventListener('message', function(e) {
log.textContent += '\n' + e.data;
}, false);
worker.port.start();
worker.port.postMessage('ping');
&lt;/script&gt;
&lt;iframe src="inner.html"&gt;&lt;/iframe&gt;
</pre><p>Here is the inner HTML page:<pre>&lt;!DOCTYPE HTML&gt;
&lt;title&gt;Shared workers: demo 3 inner frame&lt;/title&gt;
&lt;pre id=log&gt;Inner log:&lt;/pre&gt;
&lt;script&gt;
var worker = new SharedWorker('test.js');
var log = document.getElementById('log');
worker.port.onmessage = function(e) {
log.textContent += '\n' + e.data;
}
&lt;/script&gt;
</pre><p>Here is the JavaScript worker:<pre>var count = 0;
onconnect = function(e) {
count += 1;
var port = e.ports[0];
port.postMessage('Hello World! You are connection #' + count);
port.onmessage = function(e) {
port.postMessage('pong');
}
}
</pre><p><a href="http://www.whatwg.org/demos/workers/shared/003/test.html">View this example online</a>.<h4 id="shared-state-using-a-shared-worker"><span class="secno">1.2.5 </span>Shared state using a shared worker</h4><p><i>This section is non-normative.</i><p>In this example, multiple windows (viewers) can be opened that
are all viewing the same map. All the windows share the same map
information, with a single worker coordinating all the viewers. Each
viewer can move around independently, but if they set any data on
the map, all the viewers are updated.<p>The main page isn't interesting, it merely provides a way to open
the viewers:<pre>&lt;!DOCTYPE HTML&gt;
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;Workers example: Multiviewer&lt;/title&gt;
&lt;script&gt;
function openViewer() {
window.open('viewer.html');
}
&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;p&gt;&lt;button type=button onclick="openViewer()"&gt;Open a new
viewer&lt;/button&gt;&lt;/p&gt;
&lt;p&gt;Each viewer opens in a new window. You can have as many viewers
as you like, they all view the same data.&lt;/p&gt;
&lt;/body&gt;
&lt;/html&gt;</pre><p>The viewer is more involved:<pre>&lt;!DOCTYPE HTML&gt;
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;Workers example: Multiviewer viewer&lt;/title&gt;
&lt;script&gt;
var worker = new SharedWorker('worker.js', 'core');
// CONFIGURATION
function configure(event) {
if (event.data.substr(0, 4) != 'cfg ') return;
var name = event.data.substr(4).split(' ', 1);
// update display to mention our name is name
document.getElementsByTagName('h1')[0].textContent += ' ' + name;
// no longer need this listener
worker.port.removeEventListener('message', configure, false);
}
worker.port.addEventListener('message', configure, false);
// MAP
function paintMap(event) {
if (event.data.substr(0, 4) != 'map ') return;
var data = event.data.substr(4).split(',');
// display tiles data[0] .. data[8]
var canvas = document.getElementById('map');
var context = canvas.getContext('2d');
for (var y = 0; y &lt; 3; y += 1) {
for (var x = 0; x &lt; 3; x += 1) {
var tile = data[y * 3 + x];
if (tile == '0')
context.fillStyle = 'green';
else
context.fillStyle = 'maroon';
fillRect(x * 50, y * 50, 50, 50);
}
}
}
worker.port.addEventListener('message', paintMap, false);
// PUBLIC CHAT
function updatePublicChat(event) {
if (event.data.substr(0, 4) != 'txt ') return;
var name = event.data.substr(4).split(' ', 1);
var message = event.data.substr(4 + length(name) + 1);
// display "&lt;name&gt; message" in public chat
var dialog = document.getElementById('public');
var dt = document.createElement('dt');
dt.textContent = name;
dialog.appendChild(dt);
var dd = document.createElement('dd');
dd.textContent = message;
dialog.appendChild(dd);
}
worker.port.addEventListener('message', updatePublicChat, false);
// PRIVATE CHAT
function startPrivateChat(event) {
if (event.data.substr(0, 4) != 'msg ') return;
var name = event.data.substr(4).split(' ', 1);
var port = event.ports[0];
// display a private chat UI
var ul = document.getElementById('private');
var li = document.createElement('li');
var h3 = document.createElement('h3');
h3.textContent = 'Private chat with ' + name;
li.appendChild(h3);
var dialog = document.createElement('dialog');
var addMessage = function(name, message) {
var dt = document.createElement('dt');
dt.textContent = name;
dialog.appendChild(dt);
var dd = document.createElement('dd');
dd.textContent = message;
dialog.appendChild(dd);
};
port.onmessage = function (event) {
addMessage(name, event.data);
};
li.appendChild(dialog);
var form = document.createElement('form');
var p = document.createElement('p');
var input = document.createElement('input');
input.size = 50;
p.appendChild(input);
p.appendChild(document.createTextNode(' '));
var button = document.createElement('button');
button.textContent = 'Post';
p.appendChild(button);
form.onsubmit = function () {
port.postMessage(input.value);
addMessage('me', input.value);
input.value = '';
return false;
};
form.appendChild(p);
li.appendChild(form);
}
worker.port.addEventListener('message', startPrivateChat, false);
worker.port.start();
&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;h1&gt;Viewer&lt;/h1&gt;
&lt;h2&gt;Map&lt;/h2&gt;
&lt;p&gt;&lt;canvas id="map" height=150 width=150&gt;&lt;/canvas&gt;&lt;/p&gt;
&lt;p&gt;
&lt;button type=button onclick="worker.port.postMessage('mov left')"&gt;Left&lt;/button&gt;
&lt;button type=button onclick="worker.port.postMessage('mov up')"&gt;Up&lt;/button&gt;
&lt;button type=button onclick="worker.port.postMessage('mov down')"&gt;Down&lt;/button&gt;
&lt;button type=button onclick="worker.port.postMessage('mov right')"&gt;Right&lt;/button&gt;
&lt;button type=button onclick="worker.port.postMessage('set 0')"&gt;Set 0&lt;/button&gt;
&lt;button type=button onclick="worker.port.postMessage('set 1')"&gt;Set 1&lt;/button&gt;
&lt;/p&gt;
&lt;h2&gt;Public Chat&lt;/h2&gt;
&lt;dialog id="public"&gt;&lt;/dialog&gt;
&lt;form onsubmit="worker.port.postMessage('txt ' + message.value); message.value = ''; return false;"&gt;
&lt;p&gt;
&lt;input type="text" name="message" size="50"&gt;
&lt;button&gt;Post&lt;/button&gt;
&lt;/p&gt;
&lt;/form&gt;
&lt;h2&gt;Private Chat&lt;/h2&gt;
&lt;ul id="private"&gt;&lt;/ul&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre><p>There are several key things worth noting about the way the
viewer is written.<p><strong>Multiple listeners</strong>. Instead of a single message
processing function, the code here attaches multiple event
listeners, each one performing a quick check to see if it is
relevant for the message. In this example it doesn't make much
difference, but if multiple authors wanted to collaborate using a
single port to communicate with a worker, it would allow for
independent code instead of changes having to all be made to a
single event handling function.<p>Registering event listeners in this way also allows you to
unregister specific listeners when you are done with them, as is
done with the <code title="">configure()</code> method in this
example.<p>Finally, the worker:<pre>
var nextName = 0;
function getNextName() {
// this could use more friendly names
// but for now just return a number
return nextName++;
}
var map = [
[0, 0, 0, 0, 0, 0, 0],
[1, 1, 0, 1, 0, 1, 1],
[0, 1, 0, 1, 0, 0, 0],
[0, 1, 0, 1, 0, 1, 1],
[0, 0, 0, 1, 0, 0, 0],
[1, 0, 0, 1, 1, 1, 1],
[1, 1, 0, 1, 1, 0, 1],
];
function wrapX(x) {
if (x &lt; 0) return wrapX(x + map[0].length);
if (x &gt;= map[0].length) return wrapX(x - map[0].length);
return x;
}
function wrapY(y) {
if (y &lt; 0) return wrapY(y + map.length);
if (y &gt;= map[0].length) return wrapY(y - map.length);
return y;
}
function sendMapData(callback) {
var data = '';
for (var y = viewer.y-1; y &lt;= viewer.y+1; y += 1) {
for (var x = viewer.x-1; x &lt;= viewer.x+1; x += 1) {
if (data != '')
data += ',';
data += map[y][x];
}
}
callback('map ' + data);
}
var viewers = {};
onconnect = function (event) {
event.ports[0]._name = getNextName();
event.ports[0]._data = { port: event.port, x: 0, y: 0, };
viewers[event.ports[0]._name] = event.port._data;
event.ports[0].postMessage('cfg ' + name);
event.ports[0].onmessage = getMessage;
sendMapData(event.ports[0].postMessage);
};
function getMessage(event) {
switch (event.data.substr(0, 4)) {
case 'mov ':
var direction = event.data.substr(4);
var dx = 0;
var dy = 0;
switch (direction) {
case 'up': dy = -1; break;
case 'down': dy = 1; break;
case 'left': dx = -1; break;
case 'right': dx = 1; break;
}
event.target._data.x = wrapX(event.target._data.x + dx);
event.target._data.y = wrapY(event.target._data.y + dy);
sendMapData(event.target.postMessage);
break;
case 'set ':
var value = event.data.substr(4);
map[event.target._data.y][event.target._data.x] = value;
for (var viewer in viewers)
sendMapData(viewers[viewer].port.postMessage);
break;
case 'txt ':
var name = event.target._name;
var message = event.data.substr(4);
for (var viewer in viewers)
viewers[viewer].port.postMessage('txt ' + name + ' ' + message);
break;
case 'msg ':
var party1 = event._data;
var party2 = viewers[event.data.substr(4).split(' ', 1)];
if (party2) {
var channel = new MessageChannel();
party1.port.postMessage('msg ' + party2.name, [channel.port1]);
party2.port.postMessage('msg ' + party1.name, [channel.port2]);
}
break;
}
}</pre><p><strong>Connecting to multiple pages</strong>. The script uses
the <code title="handler-SharedWorkerGlobalScope-onconnect"><a href="#handler-sharedworkerglobalscope-onconnect">onconnect</a></code>
event listener to listen for multiple connections.<p><strong>Direct channels</strong>. When the worker receives a
"msg" message from one viewer naming another viewer, it sets up a
direct connection between the two, so that the two viewers can
communicate directly without the worker having to proxy all the
messages.<p><a href="http://www.whatwg.org/demos/workers/multiviewer/page.html">View this example online</a>.<h4 id="delegation"><span class="secno">1.2.6 </span>Delegation</h4><p><i>This section is non-normative.</i><p>With multicore CPUs becoming prevalent, one way to obtain better
performance is to split computationally expensive tasks amongst
multiple workers. In this example, a computationally expensive task
that is to be performed for every number from 1 to 10,000,000 is
farmed out to ten subworkers.<p>The main page is as follows, it just reports the result:<pre>&lt;!DOCTYPE HTML&gt;
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;Worker example: Multicore computation&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;p&gt;Result: &lt;output id="result"&gt;&lt;/output&gt;&lt;/p&gt;
&lt;script&gt;
var worker = new Worker('worker.js');
worker.onmessage = function (event) {
document.getElementById('result').textContent = event.data;
};
&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;</pre><p>The worker itself is as follows:<pre>// settings
var num_workers = 10;
var items_per_worker = 1000000;
// start the workers
var result = 0;
var pending_workers = num_workers;
for (var i = 0; i &lt; num_workers; i += 1) {
var worker = new Worker('core.js');
worker.postMessage(i * items_per_worker);
worker.postMessage((i+1) * items_per_worker);
worker.onmessage = storeResult;
}
// handle the results
function storeResult(event) {
result += 1*event.data;
pending_workers -= 1;
if (pending_workers &lt;= 0)
postMessage(result); // finished!
}</pre><p>It consists of a loop to start the subworkers, and then a handler
that waits for all the subworkers to respond.<p>The subworkers are implemented as follows:<pre>var start;
onmessage = getStart;
function getStart(event) {
start = 1*event.data;
onmessage = getEnd;
}
var end;
function getEnd(event) {
end = 1*event.data;
onmessage = null;
work();
}
function work() {
var result = 0;
for (var i = start; i &lt; end; i += 1) {
// perform some complex calculation here
result += 1;
}
postMessage(result);
close();
}</pre><p>They receive two numbers in two events, perform the computation
for the range of numbers thus specified, and then report the result
back to the parent.<p><a href="http://www.whatwg.org/demos/workers/multicore/page.html">View this example online</a>.</p><h3 id="tutorials"><span class="secno">1.3 </span>Tutorials</h3><h4 id="creating-a-dedicated-worker"><span class="secno">1.3.1 </span>Creating a dedicated worker</h4><p><i>This section is non-normative.</i><p>Creating a worker requires a URL to a JavaScript file. The <code title="dom-Worker"><a href="#dom-worker">Worker()</a></code> constructor is invoked with the
URL to that file as its only argument; a worker is then created and
returned:<pre>var worker = new Worker('helper.js');</pre><h4 id="communicating-with-a-dedicated-worker"><span class="secno">1.3.2 </span>Communicating with a dedicated worker</h4><p><i>This section is non-normative.</i><p>Dedicated workers use <code><a href="#messageport">MessagePort</a></code> objects behind the
scenes, and thus support all the same features, such as sending
structured data, transferring binary data, and transferring other
ports.<p>To receive messages from a dedicated worker, use the <code title="handler-worker-onmessage"><a href="#handler-worker-onmessage">onmessage</a></code> <span title="event
handler IDL attributes">event handler IDL attribute</span> on the
<code><a href="#worker">Worker</a></code> object:<pre>worker.onmessage = function (event) { ... };</pre><p>You can also use the <code title="dom-EventTarget-addEventListener">addEventListener()</code> method.<p class="note">The implicit <code><a href="#messageport">MessagePort</a></code> used by
dedicated workers has its <span>port message queue</span> implicitly
enabled when it is created, so there is no equivanet to the
<code><a href="#messageport">MessagePort</a></code> interface's <code title="dom-MessagePort-start">start()</code> method on the
<code><a href="#worker">Worker</a></code> interface.<p>To <em>send</em> data to a worker, use the <code title="dom-Worker-postMessage"><a href="#dom-worker-postmessage">postMessage()</a></code> method.
Structured data can be sent over this communication channel. To send
<code>ArrayBuffer</code> objects efficiently (by transferring them
rather than cloning them), list them in an array in the second
argument.<pre>worker.postMessage({
operation: 'find-edges',
input: buffer, // an ArrayBuffer object
threshold: 0.6,
}, [buffer]);</pre><p>To receive a message inside the worker, the <code title="handler-DedicatedWorkerGlobalScope-onmessage"><a href="#handler-dedicatedworkerglobalscope-onmessage">onmessage</a></code>
<span title="event handler IDL attributes">event handler IDL
attribute</span> is used.<pre>onmessage = function (event) { ... };</pre><p>You can again also use the <code title="dom-EventTarget-addEventListener">addEventListener()</code>
method.<p>In either case, the data is provided in the event object's <code title="dom-MessageEvent-data">data</code> attribute.<p>To send messages back, you again use <code title="dom-DedicatedWorkerGlobalScope-postMessage"><a href="#dom-dedicatedworkerglobalscope-postmessage">postMessage()</a></code>.
It supports the structured data in the same manner.<pre>postMessage(event.data.input, [event.data.input]); // transfer the buffer back</pre><h4 id="shared-workers"><span class="secno">1.3.3 </span>Shared workers</h4><p><i>This section is non-normative.</i><p>Shared workers are identified in one of two ways: either by the
URL of the script used to create it, or by explicit name. When
created by name, the URL used by the first page to create the worker
with that name is the URL of the script that will be used for that
worker. This allows multiple applications on a domain to all use a
single shared worker to provide a common service, without the
applications having to keep track of a common URL for the script
used to provide the service.<p class="note">In either case, shared workers are scoped by
<span>origin</span>. Two different sites using the same names will
not collide.<p>Creating shared workers is done using the <code title="dom-SharedWorker"><a href="#dom-sharedworker">SharedWorker()</a></code> constructor. This
constructor takes the URL to the script to use for its first
argument, and the name of the worker, if any, as the second
argument.<pre>var worker = new SharedWorker('service.js');</pre><p>Communicating with shared workers is done with explicit
<code><a href="#messageport">MessagePort</a></code> objects. The object returned by the <code title="dom-SharedWorker"><a href="#dom-sharedworker">SharedWorker()</a></code> constructor holds a
reference to the port on its <code title="dom-SharedWorker-port"><a href="#dom-sharedworker-port">port</a></code> attribute.<pre>worker.port.onmessage = function (event) { ... };
worker.port.postMessage('some message');
worker.port.postMessage({ foo: 'structured'; bar: ['data', 'also', 'possible']});</pre><p>Inside the shared worker, new clients of the worker are announced
using the <code title="event-connect">connect</code> event. The port
for the new client is given by the event object's <code title="dom-messageevent-ports">ports</code> array as its first (and
only) value.<pre>onconnect = function (event) {
var newPort = event.ports[0];
// set up a listener
newPort.onmessage = function (event) { ... };
// send a message back to the port
newPort.postMessage('ready!'); // can also send structured data, of course
};</pre><h2 id="conformance-requirements"><span class="secno">2 </span>Conformance requirements</h2><p>All diagrams, examples, and notes in this specification are
non-normative, as are all sections explicitly marked non-normative.
Everything else in this specification is normative.<p>The key words "MUST", "MUST NOT", "REQUIRED", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and
"OPTIONAL" in the normative parts of this document are to be
interpreted as described in RFC2119. For readability, these words do
not appear in all uppercase letters in this specification. <a href="#refsRFC2119">[RFC2119]</a><p>Requirements phrased in the imperative as part of algorithms
(such as "strip any leading space characters" or "return false and
abort these steps") are to be interpreted with the meaning of the
key word ("must", "should", "may", etc) used in introducing the
algorithm.<p>Some conformance requirements are phrased as requirements on
attributes, methods or objects. Such requirements are to be
interpreted as requirements on user agents.<p>Conformance requirements phrased as algorithms or specific steps
may be implemented in any manner, so long as the end result is
equivalent. (In particular, the algorithms defined in this
specification are intended to be easy to follow, and not intended to
be performant.)<p>The only conformance class defined by this specification is user
agents.<p>User agents may impose implementation-specific limits on
otherwise unconstrained inputs, e.g. to prevent denial of service
attacks, to guard against running out of memory, or to work around
platform-specific limitations.<p>When support for a feature is disabled (e.g. as an emergency
measure to mitigate a security problem, or to aid in development, or
for performance reasons), user agents must act as if they had no
support for the feature whatsoever, and as if the feature was not
mentioned in this specification. For example, if a particular
feature is accessed via an attribute in a Web IDL interface, the
attribute itself would be omitted from the objects that implement
that interface &mdash; leaving the attribute on the object but
making it return null or throw an exception is insufficient.<h3 id="dependencies"><span class="secno">2.1 </span>Dependencies</h3><p>This specification relies on several other underlying
specifications.<dl><dt>HTML</dt>
<dd>
<p>Many fundamental concepts from HTML are used by this
specification. <a href="#refsHTML">[HTML]</a></p>
</dd>
<dt>WebIDL</dt>
<dd>
<p>The IDL blocks in this specification use the semantics of the
WebIDL specification. <a href="#refsWEBIDL">[WEBIDL]</a></p>
</dd>
</dl><h2 id="terminology"><span class="secno">3 </span>Terminology</h2><p>The construction "a <code title="">Foo</code> object", where
<code title="">Foo</code> is actually an interface, is sometimes
used instead of the more accurate "an object implementing the
interface <code title="">Foo</code>".<p>The term DOM is used to refer to the API set made available to
scripts in Web applications, and does not necessarily imply the
existence of an actual <code>Document</code> object or of any other
<code>Node</code> objects as defined in the DOM Core
specifications. <a href="#refsDOMCORE">[DOMCORE]</a><p>An IDL attribute is said to be <em>getting</em> when its value is
being retrieved (e.g. by author script), and is said to be
<em>setting</em> when a new value is assigned to it.<p>The term "JavaScript" is used to refer to ECMA262, rather than
the official term ECMAScript, since the term JavaScript is more
widely known. <a href="#refsECMA262">[ECMA262]</a><h2 id="infrastructure"><span class="secno">4 </span>Infrastructure</h2><p>There are two kinds of workers; dedicated workers, and shared
workers. Dedicated workers, once created, and are linked to their
creator; but message ports can be used to communicate from a
dedicated worker to multiple other browsing contexts or
workers. Shared workers, on the other hand, are named, and once
created any script running in the same <span>origin</span> can
obtain a reference to that worker and communicate with it.<h3 id="dependencies-0"><span class="secno">4.1 </span>Dependencies</h3><p>The <dfn id="messageport"><code>MessagePort</code></dfn> interface is defined in
the HTML specification. <a href="#refsHTML">[HTML]</a><h3 id="the-global-scope"><span class="secno">4.2 </span>The global scope</h3><p>The global scope is the "inside" of a worker.<h4 id="the-workerglobalscope-abstract-interface"><span class="secno">4.2.1 </span>The <code><a href="#workerglobalscope">WorkerGlobalScope</a></code> abstract interface</h4><pre class="idl">interface <dfn id="workerglobalscope">WorkerGlobalScope</dfn> : <span>EventTarget</span> {
readonly attribute <a href="#workerglobalscope">WorkerGlobalScope</a> <a href="#dom-workerglobalscope-self" title="dom-WorkerGlobalScope-self">self</a>;
readonly attribute <a href="#workerlocation">WorkerLocation</a> <a href="#dom-workerglobalscope-location" title="dom-WorkerGlobalScope-location">location</a>;
void <a href="#dom-workerglobalscope-close" title="dom-WorkerGlobalScope-close">close</a>();
attribute <span>Function</span>? <a href="#handler-workerglobalscope-onerror" title="handler-WorkerGlobalScope-onerror">onerror</a>;
attribute <span>Function</span>? <a href="#handler-workerglobalscope-onoffline" title="handler-WorkerGlobalScope-onoffline">onoffline</a>;
attribute <span>Function</span>? <a href="#handler-workerglobalscope-ononline" title="handler-WorkerGlobalScope-ononline">ononline</a>;
};
<a href="#workerglobalscope">WorkerGlobalScope</a> implements <a href="#workerutils">WorkerUtils</a>;</pre><p>The <dfn id="dom-workerglobalscope-self" title="dom-WorkerGlobalScope-self"><code>self</code></dfn> attribute
must return the <code><a href="#workerglobalscope">WorkerGlobalScope</a></code> object itself.<p>The <dfn id="dom-workerglobalscope-location" title="dom-WorkerGlobalScope-location"><code>location</code></dfn>
attribute must return the <code><a href="#workerlocation">WorkerLocation</a></code> object created
for the <code><a href="#workerglobalscope">WorkerGlobalScope</a></code> object when the worker was
created. It represents the <span>absolute URL</span> of the script
that was used to initialize the worker, after any redirects.<hr><p>When a script invokes the <dfn id="dom-workerglobalscope-close" title="dom-WorkerGlobalScope-close"><code>close()</code></dfn>
method on a <code><a href="#workerglobalscope">WorkerGlobalScope</a></code> object, the user agent
must run the following steps (atomically):<ol><li><p>Discard any <span title="concept-task">tasks</span> that
have been added to the <span>event loop</span>'s <span title="task
queue">task queues</span>.</p>
<li><p>Set the worker's <code><a href="#workerglobalscope">WorkerGlobalScope</a></code> object's
<a href="#dom-workerglobalscope-closing" title="dom-WorkerGlobalScope-closing">closing</a> flag to
true. (This prevents any further tasks from being queued.)</li>
</ol><p>The following are the <span>event handlers</span> (and their
corresponding <span title="event handler event type">event handler
event types</span>) that must be supported, as IDL attributes, by
objects implementing the <code><a href="#workerglobalscope">WorkerGlobalScope</a></code>
interface:<table><thead><tr><th><span title="event handlers">Event handler</span> <th><span>Event handler event type</span>
<tbody><tr><td><dfn id="handler-workerglobalscope-onerror" title="handler-WorkerGlobalScope-onerror"><code>onerror</code></dfn> <td> <code title="event-error">error</code>
<tr><td><dfn id="handler-workerglobalscope-onoffline" title="handler-WorkerGlobalScope-onoffline"><code>onoffline</code></dfn> <td> <code title="event-offline">offline</code>
<tr><td><dfn id="handler-workerglobalscope-ononline" title="handler-WorkerGlobalScope-ononline"><code>ononline</code></dfn> <td> <code title="event-online">online</code>
</table><hr><p>The <code><a href="#workerglobalscope">WorkerGlobalScope</a></code> interface must not exist if
the interface's <span>relevant namespace object</span> is a
<code>Window</code> object. <a href="#refsWEBIDL">[WEBIDL]</a><h4 id="dedicated-workers-and-the-dedicatedworkerglobalscope-interface"><span class="secno">4.2.2 </span>Dedicated workers and the <code><a href="#dedicatedworkerglobalscope">DedicatedWorkerGlobalScope</a></code> interface</h4><pre class="idl">[Supplemental, NoInterfaceObject]
interface <dfn id="dedicatedworkerglobalscope">DedicatedWorkerGlobalScope</dfn> : <a href="#workerglobalscope">WorkerGlobalScope</a> {
void <a href="#dom-dedicatedworkerglobalscope-postmessage" title="dom-DedicatedWorkerGlobalScope-postMessage">postMessage</a>(any message, optional sequence&lt;<span>Transferable</span>&gt; transfer);
attribute <span>Function</span>? <a href="#handler-dedicatedworkerglobalscope-onmessage" title="handler-DedicatedWorkerGlobalScope-onmessage">onmessage</a>;
};</pre><p><code><a href="#dedicatedworkerglobalscope">DedicatedWorkerGlobalScope</a></code> objects act as if they
had an implicit <code><a href="#messageport">MessagePort</a></code> associated with them. This
port is part of a channel that is set up when the worker is created,
but it is not exposed. This object must never be garbage collected
before the <code><a href="#dedicatedworkerglobalscope">DedicatedWorkerGlobalScope</a></code> object.<p>All messages received by that port must immediately be retargeted
at the <code><a href="#dedicatedworkerglobalscope">DedicatedWorkerGlobalScope</a></code> object.<p>The <dfn id="dom-dedicatedworkerglobalscope-postmessage" title="dom-DedicatedWorkerGlobalScope-postMessage"><code>postMessage()</code></dfn> method on
<code><a href="#dedicatedworkerglobalscope">DedicatedWorkerGlobalScope</a></code> objects must act as if, when
invoked, it immediately invoked the
method of the same name on the port, with the same arguments, and
returned the same return value.<p>The following are the <span>event handlers</span> (and their
corresponding <span title="event handler event type">event handler
event types</span>) that must be supported, as IDL attributes, by
objects implementing the <code><a href="#dedicatedworkerglobalscope">DedicatedWorkerGlobalScope</a></code>
interface:<table><thead><tr><th><span title="event handlers">Event handler</span> <th><span>Event handler event type</span>
<tbody><tr><td><dfn id="handler-dedicatedworkerglobalscope-onmessage" title="handler-DedicatedWorkerGlobalScope-onmessage"><code>onmessage</code></dfn> <td> <code title="event-message">message</code>
</table><p>For the purposes of the <span>application cache</span> networking
model, a dedicated worker is an extension of the <span>cache
host</span> from which it was created.<h4 id="shared-workers-and-the-sharedworkerglobalscope-interface"><span class="secno">4.2.3 </span>Shared workers and the <code><a href="#sharedworkerglobalscope">SharedWorkerGlobalScope</a></code> interface</h4><pre class="idl">[Supplemental, NoInterfaceObject]
interface <dfn id="sharedworkerglobalscope">SharedWorkerGlobalScope</dfn> : <a href="#workerglobalscope">WorkerGlobalScope</a> {
readonly attribute DOMString <a href="#dom-sharedworkerglobalscope-name" title="dom-SharedWorkerGlobalScope-name">name</a>;
readonly attribute <span>ApplicationCache</span> <span title="dom-SharedWorkerGlobalScope-applicationCache">applicationCache</span>;
attribute <span>Function</span>? <a href="#handler-sharedworkerglobalscope-onconnect" title="handler-SharedWorkerGlobalScope-onconnect">onconnect</a>;
};</pre><p>Shared workers receive message ports through <code title="event-WorkerGlobalScope-connect">connect</code> events on
their global object for each connection.<p>The <dfn id="dom-sharedworkerglobalscope-name" title="dom-SharedWorkerGlobalScope-name"><code>name</code></dfn>
attribute must return the value it was assigned when the
<code><a href="#sharedworkerglobalscope">SharedWorkerGlobalScope</a></code> object was created by the
"<a href="#run-a-worker">run a worker</a>" algorithm. Its value represents the name
that can be used to obtain a reference to the worker using the
<code><a href="#sharedworker">SharedWorker</a></code> constructor.<p>The following are the <span>event handlers</span> (and their
corresponding <span title="event handler event type">event handler
event types</span>) that must be supported, as IDL attributes, by
objects implementing the <code><a href="#sharedworkerglobalscope">SharedWorkerGlobalScope</a></code>
interface:<table><thead><tr><th><span title="event handlers">Event handler</span> <th><span>Event handler event type</span>
<tbody><tr><td><dfn id="handler-sharedworkerglobalscope-onconnect" title="handler-SharedWorkerGlobalScope-onconnect"><code>onconnect</code></dfn> <td> <code title="event-connect">connect</code>
</table><p>For the purposes of the <span>application cache</span> networking
model, a shared worker is its own <span>cache host</span>. The
<a href="#run-a-worker">run a worker</a> algorithm takes care of associating the
worker with an <span>application cache</span>.<p class="note">The <code title="dom-SharedWorkerGlobalScope-applicationCache">applicationCache</code>
attribute returns the <code>ApplicationCache</code> object for the
worker.</p><h3 id="origins-of-workers"><span class="secno">4.3 </span>Origins of workers</h3><p>Both the <span>origin</span> and <span>effective script
origin</span> of scripts running in workers are the
<span>origin</span> of the <span>absolute URL</span> given in that
the worker's <code title="dom-WorkerGlobalScope-location"><a href="#dom-workerglobalscope-location">location</a></code> attribute
represents.<h3 id="the-event-loop"><span class="secno">4.4 </span>The event loop</h3><p>Each <code><a href="#workerglobalscope">WorkerGlobalScope</a></code> object has an <span>event
loop</span> distinct from those defined for <span title="unit of
related similar-origin browsing contexts">units of related
similar-origin browsing contexts</span>. This <span>event
loop</span> has no associated <span>browsing context</span>, and its
<span title="task queue">task queues</span> only have events,
callbacks, and networking activity as <span title="concept-task">tasks</span>. The processing model of these
<span title="event loop">event loops</span> is defined below in the
<a href="#run-a-worker">run a worker</a> algorithm.<p>Each <code><a href="#workerglobalscope">WorkerGlobalScope</a></code> object also has a <dfn id="dom-workerglobalscope-closing" title="dom-WorkerGlobalScope-closing">closing</dfn> flag, which must
initially be false, but which can get set to true by the algorithms
in the processing model section below.<p>Once the <code><a href="#workerglobalscope">WorkerGlobalScope</a></code>'s <a href="#dom-workerglobalscope-closing" title="dom-WorkerGlobalScope-closing">closing</a> flag is set to
true, the <span>event loop</span>'s <span title="task queue">task
queues</span> must discard any further <span title="concept-task">tasks</span> that would be added to them (tasks
already on the queue are unaffected except where otherwise
specified). Effectively, once the <a href="#dom-workerglobalscope-closing" title="dom-WorkerGlobalScope-closing">closing</a> flag is true,
timers stop firing, notifications for all pending asynchronous
operations are dropped, etc.<h3 id="the-worker-s-lifetime"><span class="secno">4.5 </span>The worker's lifetime</h3><p>Workers communicate with other workers and with <span title="browsing context">browsing contexts</span> through <span title="channel messaging">message channels</span> and their
<code><a href="#messageport">MessagePort</a></code> objects.<p>Each <code><a href="#workerglobalscope">WorkerGlobalScope</a></code> <var title="">worker global
scope</var> has a list of <dfn id="the-worker-s-ports">the worker's ports</dfn>, which
consists of all the <code><a href="#messageport">MessagePort</a></code> objects that are
entangled with another port and that have one (but only one) port
owned by <var title="">worker global scope</var>. This list includes
the implicit
<code><a href="#messageport">MessagePort</a></code> in the case of <a href="#dedicatedworkerglobalscope" title="DedicatedWorkerGlobalScope">dedicated workers</a>.<p>Each <code><a href="#workerglobalscope">WorkerGlobalScope</a></code> also has a list of <dfn id="the-worker-s-workers">the
worker's workers</dfn>. Initially this list is empty; it is
populated when the worker creates or obtains further workers.<p>Finally, each <code><a href="#workerglobalscope">WorkerGlobalScope</a></code> also has a list of
<dfn id="the-worker-s-documents">the worker's <code>Document</code>s</dfn>. Initially this list
is empty; it is populated when the worker is created.<p>Whenever a <code>Document</code> <var title="">d</var> is <dfn id="add-a-document-to-the-worker-s-documents" title="add a document to the worker's documents">added to the
worker's <code>Document</code>s</dfn>, the user agent must, for each
worker in the list of <a href="#the-worker-s-workers">the worker's workers</a> whose list
of <a href="#the-worker-s-documents">the worker's <code>Document</code>s</a> does not contain
<var title="">d</var>, <a href="#add-a-document-to-the-worker-s-documents" title="add a document to the worker's
documents">add <var title="">d</var> to <var title="">q</var>'s
<code>WorkerGlobalScope</code> owner's list of <span>the worker's
<code>Document</code>s</span></a>.</p><p>Whenever a <code>Document</code> object is <span title="discard a
Document">discarded</span>, it must be removed from the list of
<a href="#the-worker-s-documents">the worker's <code>Document</code>s</a> of each worker
whose list contains that <code>Document</code>.<p>Given a <span>script's global object</span> <var title="">o</var>
when creating or obtaining a worker, the <dfn id="list-of-relevant-document-objects-to-add">list of relevant
<code>Document</code> objects to add</dfn> depends on the type of
<var title="">o</var>. If <var title="">o</var> is a
<code><a href="#workerglobalscope">WorkerGlobalScope</a></code> object (i.e. if we are creating a
nested worker), then the relevant <code>Document</code>s are the
<code>Document</code>s that are in <var title="">o</var>'s own list
of <a href="#the-worker-s-documents">the worker's <code>Document</code>s</a>. Otherwise, <var title="">o</var> is a <code>Window</code> object, and the relevant
<code>Document</code> is just the <code>Document</code> that is the
<span>active document</span> of the <code>Window</code> object <var title="">o</var>.<hr><p>A worker is said to be a <dfn id="permissible-worker">permissible worker</dfn> if its
list of <a href="#the-worker-s-documents">the worker's <code>Document</code>s</a> is not
empty.<p>A worker is said to be a <dfn id="protected-worker">protected worker</dfn> if it is a
<a href="#permissible-worker">permissible worker</a> and either it has outstanding
timers, database transactions, or network connections, or its list
of <a href="#the-worker-s-ports">the worker's ports</a> is not empty, or its
<code><a href="#workerglobalscope">WorkerGlobalScope</a></code> is actually a
<code><a href="#sharedworkerglobalscope">SharedWorkerGlobalScope</a></code> object (i.e. the worker is a
shared worker).<p>A worker is said to be an <dfn id="active-needed-worker">active needed worker</dfn> if any
of the <code>Document</code> objects in <a href="#the-worker-s-documents">the worker's
<code>Document</code>s</a> are <span>fully active</span>.<p>A worker is said to be a <dfn id="suspendable-worker">suspendable worker</dfn> if it is
not an <a href="#active-needed-worker">active needed worker</a> but it is a
<a href="#permissible-worker">permissible worker</a>.<h3 id="processing-model"><span class="secno">4.6 </span>Processing model</h3><p>When a user agent is to <dfn id="run-a-worker">run a worker</dfn> for a script with
<span>URL</span> <var title="">url</var>, a <span>browsing
context</span> <var title="">owner browsing context</var>, a
<code>Document</code> <var title="">owner document</var>, an
<span>origin</span> <var title="">owner origin</var>, and with
global scope <var title="">worker global scope</var>, it must run
the following steps:<ol><li>
<p>Create a separate parallel execution environment (i.e. a
separate thread or process or equivalent construct), and run the
rest of these steps asynchronously in that context.</p>
</li>
<li><p>If <var title="">worker global scope</var> is actually a
<code><a href="#sharedworkerglobalscope">SharedWorkerGlobalScope</a></code> object (i.e. the worker is a
shared worker), and there are any <span title="relevant application
cache">relevant application caches</span> that are identified by a
manifest URL with the <span>same origin</span> as <var title="">url</var> and that have <var title="">url</var> as one of
their entries, <em>not</em> excluding entries marked as <span title="concept-appcache-foreign">foreign</span>, then associate the
<var title="">worker global scope</var> with the <span title="concept-appcache-selection">most appropriate application
cache</span> of those that match.</li>
<li>
<p>Attempt to <span>fetch</span> the resource identified by <var title="">url</var>, from the <var title="">owner origin</var>,
with the <i>synchronous flag</i> set and the <i>force same-origin
flag</i> set.</p>
<p>If the attempt fails, then for each <code><a href="#worker">Worker</a></code> or
<code><a href="#sharedworker">SharedWorker</a></code> object associated with <var title="">worker global scope</var>, <span>queue a task</span> to
<span>fire a simple event</span> named <code title="event-error">error</code> at that object. Abort these
steps.</p>
<p>If the attempt succeeds, then let <var title="">source</var> be
the script resource <span>decoded as UTF-8, with error
handling</span>.
<a href="#refsHTML">[HTML]</a>
</p>
<p>Let <var title="">language</var> be JavaScript.</p>
<p class="note">As with <code>script</code> elements, the MIME
type of the script is ignored. Unlike with <code>script</code>
elements, there is no way to override the type. It's always
assumed to be JavaScript.</p>
</li>
<li>
<p>A new <span title="concept-script">script</span> is now
created, as follows.</p>
<p>Create a new <span>script execution environment</span>
set up as appropriate for the scripting language <var title="">language</var>.</p>
<p>Parse/compile/initialize <var title="">source</var> using that
<span>script execution environment</span>, as appropriate for <var title="">language</var>, and thus obtain a <span>list of code
entry-points</span>; set the <i>initial code entry-point</i> to
the entry-point for any executable code to be immediately run.</p>
<p>Set the <span>script's global object</span> to <var title="">worker global scope</var>.</p>
<p>Set the <span>script's browsing context</span> to <var title="">owner browsing context</var>.</p>
<p>Set the <span>script's document</span> to <var title="">owner
document</var>.</p>
<p>Set the <span>script's URL character encoding</span> to
UTF-8. (This is just used for encoding non-ASCII characters in the
query component of URLs.)</p>
<p>Set the <span>script's base URL</span> to <var title="">url</var>.</p>
</li>
<li>
<p><strong>Closing orphan workers</strong>: Start monitoring the
worker such that no sooner than it stops being either a
<a href="#protected-worker">protected worker</a> or a <a href="#suspendable-worker">suspendable
worker</a>, and no later than it stops being a
<a href="#permissible-worker">permissible worker</a>, <var title="">worker global
scope</var>'s <a href="#dom-workerglobalscope-closing" title="dom-WorkerGlobalScope-closing">closing</a> flag is set
to true.</p>
</li>
<li>
<p><strong>Suspending workers</strong>: Start monitoring the
worker, such that whenever <var title="">worker global
scope</var>'s <a href="#dom-workerglobalscope-closing" title="dom-WorkerGlobalScope-closing">closing</a> flag is false
and the worker is a <a href="#suspendable-worker">suspendable worker</a>, the user
agent suspends execution of script in that worker until such time
as either the <a href="#dom-workerglobalscope-closing" title="dom-WorkerGlobalScope-closing">closing</a> flag switches
to true or the worker stops being a <a href="#suspendable-worker">suspendable
worker</a>.</p>
</li>
<li>
<p><span title="jump to a code entry-point">Jump</span> to the
<span title="concept-script">script</span>'s <i>initial code
entry-point</i>, and let that run until it either returns, fails
to catch an exception, or gets prematurely aborted by the
"<a href="#kill-a-worker">kill a worker</a>" or "<a href="#terminate-a-worker">terminate a worker</a>"
algorithms defined below.</p>
</li>
<li><p>If <var title="">worker global scope</var> is actually a
<code><a href="#dedicatedworkerglobalscope">DedicatedWorkerGlobalScope</a></code> object (i.e. the worker is
a dedicated worker), then enable the <span>port message
queue</span> of the worker's implicit port.</li>
<li>
<p><i title="">Event loop</i>: Wait until either there is a <span title="concept-task">task</span> in one of the <span>event
loop</span>'s <span title="task queue">task queues</span> or <var title="">worker global scope</var>'s <a href="#dom-workerglobalscope-closing" title="dom-WorkerGlobalScope-closing">closing</a> flag is set
to true.</p>
</li>
<li>
<p>Run the oldest task on one of the <span>event loop</span>'s
<span title="task queue">task queues</span>, if any. The user
agent may pick any <span>task queue</span>.</p>
<p class="note">The handling of events or the execution of
callbacks might get prematurely aborted by the "<a href="#kill-a-worker">kill a
worker</a>" or "<a href="#terminate-a-worker">terminate a worker</a>" algorithms
defined below.</p>
</li>
<li>
<p>If the <span>storage mutex</span> is now owned by the worker's
<span>event loop</span>, release it so that it is once again
free.</p>
</li>
<li>
<p>Remove the task just run in the earlier step, if any, from its
<span>task queue</span>.</p>
</li>
<li>
<p>If there are any more events in the <span>event loop</span>'s
<span title="task queue">task queues</span> or if <var title="">worker global scope</var>'s <a href="#dom-workerglobalscope-closing" title="dom-WorkerGlobalScope-closing">closing</a> flag is set
to false, then jump back to the step above labeled <i>event
loop</i>.</p>
</li>
<li>
<p>Empty the <var title="">worker global scope</var>'s <span>list
of active timeouts</span> and its <span>list of active
intervals</span>.</p>
</li>
<li>
<p>Disentangle all the ports in the list of <a href="#the-worker-s-ports">the worker's
ports</a>.</p>
</li>
</ol><hr><p>When a user agent is to <dfn id="kill-a-worker">kill a worker</dfn> it must
run the following steps in parallel with the worker's main loop (the
"<a href="#run-a-worker">run a worker</a>" processing model defined above):<ol><li><p>Set the worker's <code><a href="#workerglobalscope">WorkerGlobalScope</a></code> object's <a href="#dom-workerglobalscope-closing" title="dom-WorkerGlobalScope-closing">closing</a> flag to
true.</li>
<li><p>If there are any <span title="concept-task">tasks</span>
queued in the <span>event loop</span>'s <span title="task
queue">task queues</span>, discard them without processing them.</li>
<li><p>Wait a user-agent-defined amount of time.</li>
<li><p>Abort the script currently running in the worker.</li>
</ol><p>User agents may invoke the "<a href="#kill-a-worker">kill a worker</a>"
processing model on a worker at any time, e.g. in response to user
requests, in response to CPU quota management, or when a worker
stops being an <a href="#active-needed-worker">active needed worker</a> if the worker
continues executing even after its <a href="#dom-workerglobalscope-closing" title="dom-WorkerGlobalScope-closing">closing</a> flag was
set to true.<hr><p>When a user agent is to <dfn id="terminate-a-worker">terminate a worker</dfn> it must run
the following steps in parallel with the worker's main loop (the
"<a href="#run-a-worker">run a worker</a>" processing model defined above):<ol><li><p>Set the worker's <code><a href="#workerglobalscope">WorkerGlobalScope</a></code> object's
<a href="#dom-workerglobalscope-closing" title="dom-WorkerGlobalScope-closing">closing</a> flag to
true.</li>
<li><p>If there are any <span title="concept-task">tasks</span>
queued in the <span>event loop</span>'s <span title="task
queue">task queues</span>, discard them without processing
them.</li>
<li><p>Abort the script currently running in the worker.</li>
<li><p>If the worker's <code><a href="#workerglobalscope">WorkerGlobalScope</a></code> object is
actually a <code><a href="#dedicatedworkerglobalscope">DedicatedWorkerGlobalScope</a></code> object (i.e. the
worker is a dedicated worker), then empty the <span>port message
queue</span> of the port that the worker's implicit port is
entangled with.</li>
</ol><hr><p>The <span>task source</span> for the tasks mentioned above is the
<span>DOM manipulation task source</span>.<h3 id="runtime-script-errors"><span class="secno">4.7 </span>Runtime script errors</h3><p>Whenever an uncaught runtime script error occurs in one of the
worker's scripts, if the error did not occur while handling a
previous script error, the user agent must <span>report the
error</span> using the <code><a href="#workerglobalscope">WorkerGlobalScope</a></code> object's <code title="handler-WorkerGlobalScope-onerror"><a href="#handler-workerglobalscope-onerror">onerror</a></code>
attribute.
<a href="#refsHTML">[HTML]</a>
<p>For shared workers, if the error is still <i title="concept-error-nothandled">not handled</i> afterwards, or if
the error occurred while handling a previous script error, the error
may be reported to the user.
<a href="#refsHTML">[HTML]</a>
<p>For dedicated workers, if the error is still <i title="concept-error-nothandled">not handled</i> afterwards, or if
the error occurred while handling a previous script error, the user
agent must <span>queue a task</span> to fire an event that uses the
<code><a href="#errorevent">ErrorEvent</a></code> interface, with the name <code title="event-error">error</code>, that doesn't bubble and is
cancelable, with its <code title="dom-ErrorEvent-message"><a href="#dom-errorevent-message">message</a></code>, <code title="dom-ErrorEvent-filename"><a href="#dom-errorevent-filename">filename</a></code>, and <code title="dom-ErrorEvent-lineno"><a href="#dom-errorevent-lineno">lineno</a></code> attributes set
appropriately, at the <code><a href="#worker">Worker</a></code> object associated with the
worker. If the event is not canceled, the user agent must act as if the
uncaught runtime script error had occurred in the global scope that
the <code><a href="#worker">Worker</a></code> object is in, thus repeating the entire
runtime script error reporting process one level up.<p>If the implicit port connecting the worker to its
<code><a href="#worker">Worker</a></code> object has been disentangled (i.e. if the parent
worker has been terminated), then the user agent must act as if the
<code><a href="#worker">Worker</a></code> object had no <code title="event-error">error</code> event handler and as if that
worker's <code title="handler-WorkerGlobalScope-onerror"><a href="#handler-workerglobalscope-onerror">onerror</a></code> attribute
was null, but must otherwise act as described above.<p class="note">Thus, error reports proagate up to the chain of
dedicated workers up to the original <code>Document</code>, even if
some of the workers along this chain have been terminated and
garbage collected.<p>The <span>task source</span> for the task mentioned above is the
<span>DOM manipulation task source</span>.<hr><pre class="idl">interface <dfn id="errorevent">ErrorEvent</dfn> : <span>Event</span> {
readonly attribute DOMString <a href="#dom-errorevent-message" title="dom-ErrorEvent-message">message</a>;
readonly attribute DOMString <a href="#dom-errorevent-filename" title="dom-ErrorEvent-filename">filename</a>;
readonly attribute unsigned long <a href="#dom-errorevent-lineno" title="dom-ErrorEvent-lineno">lineno</a>;
void <a href="#dom-errorevent-initerrorevent" title="dom-ErrorEvent-initErrorEvent">initErrorEvent</a>(DOMString typeArg, boolean canBubbleArg, boolean cancelableArg, DOMString messageArg, DOMString filenameArg, unsigned long linenoArg);
};</pre><p>The <dfn id="dom-errorevent-initerrorevent" title="dom-ErrorEvent-initErrorEvent"><code>initErrorEvent()</code></dfn>
method must initialize the event in a manner analogous to the
similarly-named method in the DOM Events interfaces. <a href="#refsDOMEVENTS">[DOMEVENTS]</a><p>The <dfn id="dom-errorevent-message" title="dom-ErrorEvent-message"><code>message</code></dfn>
attribute represents the error message.<p>The <dfn id="dom-errorevent-filename" title="dom-ErrorEvent-filename"><code>filename</code></dfn>
attribute represents the <span>absolute URL</span> of the script in
which the error originally occurred.<p>The <dfn id="dom-errorevent-lineno" title="dom-ErrorEvent-lineno"><code>lineno</code></dfn>
attribute represents the line number where the error occurred in the
script.<h3 id="creating-workers"><span class="secno">4.8 </span>Creating workers</h3><h4 id="the-abstractworker-abstract-interface"><span class="secno">4.8.1 </span>The <code><a href="#abstractworker">AbstractWorker</a></code> abstract interface</h4><pre class="idl">[Supplemental, NoInterfaceObject]
interface <dfn id="abstractworker">AbstractWorker</dfn> : <span>EventTarget</span> {
attribute <span>Function</span>? <a href="#handler-abstractworker-onerror" title="handler-AbstractWorker-onerror">onerror</a>;
};</pre><p>The following are the <span>event handlers</span> (and their
corresponding <span title="event handler event type">event handler
event types</span>) that must be supported, as IDL attributes, by
objects implementing the <code><a href="#abstractworker">AbstractWorker</a></code> interface:<table><thead><tr><th><span title="event handlers">Event handler</span> <th><span>Event handler event type</span>
<tbody><tr><td><dfn id="handler-abstractworker-onerror" title="handler-AbstractWorker-onerror"><code>onerror</code></dfn> <td> <code title="event-error">error</code>
</table><h4 id="dedicated-workers-and-the-worker-interface"><span class="secno">4.8.2 </span>Dedicated workers and the <code><a href="#worker">Worker</a></code> interface</h4><pre class="idl">[<a href="#dom-worker" title="dom-Worker">Constructor</a>(DOMString scriptURL)]
interface <dfn id="worker">Worker</dfn> : <a href="#abstractworker">AbstractWorker</a> {
void <a href="#dom-worker-terminate" title="dom-Worker-terminate">terminate</a>();
void <a href="#dom-worker-postmessage" title="dom-Worker-postMessage">postMessage</a>(any message, optional sequence&lt;<span>Transferable</span>&gt; transfer); attribute <span>Function</span>? <a href="#handler-worker-onmessage" title="handler-Worker-onmessage">onmessage</a>;
};</pre><p>The <dfn id="dom-worker-terminate" title="dom-Worker-terminate"><code>terminate()</code></dfn> method,
when invoked, must cause the "<a href="#terminate-a-worker">terminate a worker</a>"
algorithm to be run on the worker with with the object is
associated.<p><code><a href="#worker">Worker</a></code> objects act as if they had an implicit
<code><a href="#messageport">MessagePort</a></code> associated with them. This port is part of
a channel that is set up when the worker is created, but it is not
exposed. This object must never be garbage collected before the
<code><a href="#worker">Worker</a></code> object.<p>All messages received by that port must immediately be retargeted
at the <code><a href="#worker">Worker</a></code> object.<p>The <dfn id="dom-worker-postmessage" title="dom-Worker-postMessage"><code>postMessage()</code></dfn> method on <code><a href="#worker">Worker</a></code> objects
must act as if, when invoked, it
immediately invoked the method of the same name on the port, with
the same arguments, and returned the same return value.<p>The following are the <span>event handlers</span> (and their
corresponding <span title="event handler event type">event handler
event types</span>) that must be supported, as IDL attributes, by
objects implementing the <code><a href="#worker">Worker</a></code> interface:<table><thead><tr><th><span title="event handlers">Event handler</span> <th><span>Event handler event type</span>
<tbody><tr><td><dfn id="handler-worker-onmessage" title="handler-Worker-onmessage"><code>onmessage</code></dfn> <td> <code title="event-message">message</code>
</table><hr><p>When the <dfn id="dom-worker" title="dom-Worker"><code>Worker(<var title="">scriptURL</var>)</code></dfn> constructor is invoked, the
user agent must run the following steps:<ol><li><p><span title="resolve a url">Resolve</span> the <var title="">scriptURL</var> argument relative to the <span>entry
script</span>'s <span title="script's base URL">base URL</span>,
when the method is invoked.</li>
<li><p>If this fails, throw a <code>SYNTAX_ERR</code>
exception.</li>
<li>
<p>If the <span>origin</span> of the resulting <span>absolute
URL</span> is not the <span title="same origin">same</span> as the
origin of the <span>entry script</span>, then throw a
<code>SECURITY_ERR</code> exception.</p>
<p class="note">Thus, scripts must be external files with the same
scheme as the original page: you can't load a script from a <span title="data protocol"><code title="">data:</code> URL</span> or
<span title="javascript protocol"><code title="">javascript:</code> URL</span>, and an <code>https:</code>
page couldn't start workers using scripts with <code>http:</code>
URLs.</p>
</li>
<li><p>Create a new <code><a href="#dedicatedworkerglobalscope">DedicatedWorkerGlobalScope</a></code>
object. Let <var title="">worker global scope</var> be this new
object.</li>
<li><p>Create a new <code><a href="#worker">Worker</a></code> object, associated with
<var title="">worker global scope</var>. Let <var title="">worker</var> be this new object.</li>
<li><p><span>Create a new <code><a href="#messageport">MessagePort</a></code> object</span>
owned by the <span title="script's global object">global
object</span> of the <span title="concept-script">script</span> that
invoked the constructor. Let this be the <var title="">outside
port</var>.</li>
<li><p>Associate the <var title="">outside port</var> with <var title="">worker</var>.</li>
<li><p><span>Create a new <code><a href="#messageport">MessagePort</a></code> object</span>
owned by <var title="">worker global scope</var>. Let <var title="">inside port</var> be this new object.</li>
<li><p>Associate <var title="">inside port</var> with <var title="">worker global scope</var>.</li>
<li><p><span>Entangle</span> <var title="">outside port</var> and
<var title="">inside port</var>.</li>
<li><p>Return <var title="">worker</var>, and run the following
steps asynchronously.</li>
<li><p>Enable <var title="">outside port</var>'s <span>port message
queue</span>.</li>
<li>
<p>Let <var title="">docs</var> be the <a href="#list-of-relevant-document-objects-to-add">list of relevant
<code>Document</code> objects to add</a> given the <span title="script's global object">global object</span> of the <span title="concept-script">script</span> that invoked the
constructor.</p>
</li>
<li>
<p><a href="#add-a-document-to-the-worker-s-documents" title="add a document to the worker's documents">Add to
<var title="">worker global scope</var>'s list of <span>the
worker's <code>Document</code>s</span></a> the
<code>Document</code> objects in <var title="">docs</var>.</p>
</li>
<li>
<p>If the <span title="script's global object">global object</span>
of the <span title="concept-script">script</span> that invoked the
constructor is a <code><a href="#workerglobalscope">WorkerGlobalScope</a></code> object (i.e. we
are creating a nested worker), add <var title="">worker global
scope</var> to the list of <a href="#the-worker-s-workers">the worker's workers</a> of the
<code><a href="#workerglobalscope">WorkerGlobalScope</a></code> object that is the <span title="script's global object">global object</span> of the <span title="concept-script">script</span> that invoked the
constructor.</p>
</li>
<li>
<p><a href="#run-a-worker">Run a worker</a> for the resulting <span>absolute
URL</span>, with the <span>script's browsing context</span> of the
script that invoked the method as the <var title="">owner browsing
context</var>, with the <span>script's document</span> of the
script that invoked the method as the <var title="">owner
document</var>, with the <span>origin</span> of the <span>entry
script</span> as the <var title="">owner origin</var>, and with
<var title="">worker global scope</var> as the global scope.</p>
</li>
</ol><p>This constructor must be visible when the <span>script's global
object</span> is either a <code>Window</code> object or an object
implementing the <code><a href="#workerutils">WorkerUtils</a></code> interface.<h4 id="shared-workers-and-the-sharedworker-interface"><span class="secno">4.8.3 </span>Shared workers and the <code><a href="#sharedworker">SharedWorker</a></code> interface</h4><pre class="idl">[<a href="#dom-sharedworker" title="dom-SharedWorker">Constructor</a>(DOMString scriptURL, optional DOMString name)]
interface <dfn id="sharedworker">SharedWorker</dfn> : <a href="#abstractworker">AbstractWorker</a> {
readonly attribute <a href="#messageport">MessagePort</a> <a href="#dom-sharedworker-port" title="dom-SharedWorker-port">port</a>;
};</pre><p>The <dfn id="dom-sharedworker-port" title="dom-SharedWorker-port"><code>port</code></dfn>
attribute must return the value it was assigned by the object's
constructor. It represents the <code><a href="#messageport">MessagePort</a></code> for
communicating with the shared worker.<p>When the <dfn id="dom-sharedworker" title="dom-SharedWorker"><code>SharedWorker(<var title="">scriptURL</var>, <var title="">name</var>)</code></dfn>
constructor is invoked, the user agent must run the following
steps:<ol><li><p><span title="resolve a url">Resolve</span> the <var title="">scriptURL</var> argument.</li>
<li><p>If this fails, throw a <code>SYNTAX_ERR</code>
exception.</li>
<li><p>Otherwise, let <var title="">scriptURL</var> be the
resulting <span>absolute URL</span>.</li>
<li><p>Let <var title="">name</var> be the value of the second
argument, or the empty string if the second argument was
omitted.</li>
<li>
<p>If the <span>origin</span> of <var title="">scriptURL</var> is
not the <span title="same origin">same</span> as the origin of the
<span>entry script</span>, then throw a <code>SECURITY_ERR</code>
exception.</p>
<p class="note">Thus, scripts must be external files with the same
scheme as the original page: you can't load a script from a <span title="data protocol"><code title="">data:</code> URL</span> or
<span title="javascript protocol"><code title="">javascript:</code> URL</span>, and a <code>https:</code>
page couldn't start workers using scripts with <code>http:</code>
URLs.</p>
</li>
<li>
<p>Let <var title="">docs</var> be the <a href="#list-of-relevant-document-objects-to-add">list of relevant
<code>Document</code> objects to add</a> given the <span title="script's global object">global object</span> of the <span title="concept-script">script</span> that invoked the
constructor.</p>
</li>
<li>
<p>Execute the following substeps atomically:</p>
<ol><li><p>Create a new <code><a href="#sharedworker">SharedWorker</a></code> object, which will
shortly be associated with a <code><a href="#sharedworkerglobalscope">SharedWorkerGlobalScope</a></code>
object. Let this <code><a href="#sharedworker">SharedWorker</a></code> object be <var title="">worker</var>.</li>
<li><p><span>Create a new <code><a href="#messageport">MessagePort</a></code> object</span>
owned by the <span title="script's global object">global
object</span> of the script that invoked the method. Let this be
the <var title="">outside port</var>.</li>
<li><p>Assign <var title="">outside port</var> to the <code title="dom-SharedWorker-port"><a href="#dom-sharedworker-port">port</a></code> attribute of <var title="">worker</var>.</li>
<li><p>Let <var title="">worker global scope</var> be
null.</li>
<li><p>If <var title="">name</var> is not the empty string and
there exists a <code><a href="#sharedworkerglobalscope">SharedWorkerGlobalScope</a></code> object whose
<a href="#dom-workerglobalscope-closing" title="dom-WorkerGlobalScope-closing">closing</a> flag
is false, whose <code title="dom-WorkerGlobalScope-name">name</code> attribute is
exactly equal to <var title="">name</var>, and whose <code title="dom-WorkerGlobalScope-location"><a href="#dom-workerglobalscope-location">location</a></code> attribute
represents an <span>absolute URL</span> with the <span>same
origin</span> as <var title="">scriptURL</var>, then let <var title="">worker global scope</var> be that
<code><a href="#sharedworkerglobalscope">SharedWorkerGlobalScope</a></code> object.</li>
<li><p>Otherwise, if <var title="">name</var> is the empty string
and there exists a <code><a href="#sharedworkerglobalscope">SharedWorkerGlobalScope</a></code> object
whose <a href="#dom-workerglobalscope-closing" title="dom-WorkerGlobalScope-closing">closing</a>
flag is false, whose <code title="dom-WorkerGlobalScope-name">name</code> attribute is the
empty string, and whose <code title="dom-WorkerGlobalScope-location"><a href="#dom-workerglobalscope-location">location</a></code> attribute
represents an <span>absolute URL</span> that is exactly equal to
<var title="">scriptURL</var>, then let <var title="">worker
global scope</var> be that <code><a href="#sharedworkerglobalscope">SharedWorkerGlobalScope</a></code>
object.</li>
<li>
<p>If <var title="">worker global scope</var> is not null, then
run these steps:</p>
<ol><li><p>If <var title="">worker global scope</var>'s <code title="dom-WorkerGlobalScope-location"><a href="#dom-workerglobalscope-location">location</a></code>
attribute represents an <span>absolute URL</span> that is not
exactly equal to <var title="">scriptURL</var>, then throw a
<code>URL_MISMATCH_ERR</code> exception and abort all these
steps.</li>
<li><p>Associate <var title="">worker</var> with <var title="">worker global scope</var>.</li>
<li><p><span>Create a new <code><a href="#messageport">MessagePort</a></code>
object</span> owned by <var title="">worker global
scope</var>. Let this be the <var title="">inside
port</var>.</li>
<li><p><span>Entangle</span> <var title="">outside port</var>
and <var title="">inside port</var>.</li>
<li><p>Return <var title="">worker</var> and perform the next
step asynchronously.</li>
<li><p>Create an event that uses the <code>MessageEvent</code>
interface, with the name <code title="event-connect">connect</code>, which does not bubble, is
not cancelable, has no default action, has a <code title="dom-MessageEvent-data">data</code> attribute whose value
is the empty string and has a <code title="dom-MessageEvent-ports">ports</code> attribute whose
value is a <span title="dfn-read-only-array">read only</span>
array containing only the newly created port, and <span>queue a
task</span> to dispatch the event at <var title="">worker
global scope</var>.</li>
<li>
<p><a href="#add-a-document-to-the-worker-s-documents" title="add a document to the worker's documents">Add to
<var title="">worker global scope</var>'s list of <span>the
worker's <code>Document</code>s</span></a> the
<code>Document</code> objects in <var title="">docs</var>.</p>
</li>
<li>
<p>If the <span title="script's global object">global
object</span> of the <span title="concept-script">script</span>
that invoked the constructor is a
<code><a href="#workerglobalscope">WorkerGlobalScope</a></code> object, add <var title="">worker global scope</var> to the list of <a href="#the-worker-s-workers">the
worker's workers</a> of the <code><a href="#workerglobalscope">WorkerGlobalScope</a></code>
object that is the <span title="script's global object">global
object</span> of the <span title="concept-script">script</span>
that invoked the constructor.</p>
</li>
<li><p>Abort all these steps.</li>
</ol></li>
<li><p>Create a new <code><a href="#sharedworkerglobalscope">SharedWorkerGlobalScope</a></code>
object. Let <var title="">worker global scope</var> be this new
object.</li>
<li><p>Associate <var title="">worker</var> with <var title="">worker global scope</var>.</li>
<li><p>Set the <code title="dom-SharedWorkerGlobalScope-name"><a href="#dom-sharedworkerglobalscope-name">name</a></code> attribute of
<var title="">worker global scope</var> to <var title="">name</var>.</li>
<li><p><span>Create a new <code><a href="#messageport">MessagePort</a></code> object</span>
owned by <var title="">worker global scope</var>. Let <var title="">inside port</var> be this new object.</li>
<li><p><span>Entangle</span> <var title="">outside port</var> and
<var title="">inside port</var>.</li>
</ol></li>
<li><p>Return <var title="">worker</var> and perform the remaining
steps asynchronously.</li>
<li><p>Create an event that uses the <code>MessageEvent</code>
interface, with the name <code title="event-connect">connect</code>, which does not bubble, is not
cancelable, has no default action, has a <code title="dom-MessageEvent-data">data</code> attribute whose value is
the empty string and has a <code title="dom-MessageEvent-ports">ports</code> attribute whose value
is a <span title="dfn-read-only-array">read only</span> array
containing only the newly created port, and <span>queue a
task</span> to dispatch the event at <var title="">worker global
scope</var>.</li>
<li>
<p><a href="#add-a-document-to-the-worker-s-documents" title="add a document to the worker's documents">Add to
<var title="">worker global scope</var>'s list of <span>the
worker's <code>Document</code>s</span></a> the
<code>Document</code> objects in <var title="">docs</var>.</p>
</li>
<li>
<p>If the <span title="script's global object">global object</span>
of the <span title="concept-script">script</span> that invoked the
constructor is a <code><a href="#workerglobalscope">WorkerGlobalScope</a></code> object, add <var title="">worker global scope</var> to the list of <a href="#the-worker-s-workers">the
worker's workers</a> of the <code><a href="#workerglobalscope">WorkerGlobalScope</a></code>
object that is the <span title="script's global object">global
object</span> of the <span title="concept-script">script</span>
that invoked the constructor.</p>
</li>
<li>
<p><a href="#run-a-worker">Run a worker</a> for <var title="">scriptURL</var>,
with the <span>script's browsing context</span> of the script that
invoked the method as the <var title="">owner browsing
context</var>, with the <span>script's document</span> of the
script that invoked the method as the <var title="">owner
document</var>, with the <span>origin</span> of the <span>entry
script</span> as the <var title="">owner origin</var>, and with
<var title="">worker global scope</var> as the global scope.</p>
</li>
</ol><p>This constructor must be visible when the <span>script's global
object</span> is either a <code>Window</code> object or an object
implementing the <code><a href="#workerutils">WorkerUtils</a></code> interface.<p>The <span>task source</span> for the tasks mentioned above is the
<span>DOM manipulation task source</span>.<h2 id="apis-available-to-workers"><span class="secno">5 </span>APIs available to workers</h2><pre class="idl">[NoInterfaceObject]
interface <dfn id="workerutils">WorkerUtils</dfn> {
void <a href="#dom-workerglobalscope-importscripts" title="dom-WorkerGlobalScope-importScripts">importScripts</a>(DOMString... urls);
readonly attribute <a href="#workernavigator">WorkerNavigator</a> <a href="#dom-worker-navigator" title="dom-worker-navigator">navigator</a>;
};
<a href="#workerutils">WorkerUtils</a> implements <span>WindowTimers</span>;
<a href="#workerutils">WorkerUtils</a> implements <span>WindowBase64</span>;</pre><p>The <code>WindowTimers</code> and <code>WindowBase64</code>
interfaces are defined in the HTML specification. <a href="#refsHTML">[HTML]</a><p>The DOM APIs (<code>Node</code> objects, <code>Document</code>
objects, etc) are not available to workers in this version of this
specification.<h3 id="importing-scripts-and-libraries"><span class="secno">5.1 </span>Importing scripts and libraries</h3><p>When a script invokes the <dfn id="dom-workerglobalscope-importscripts" title="dom-WorkerGlobalScope-importScripts"><code>importScripts(<var title="">urls</var>)</code></dfn> method on a
<code><a href="#workerglobalscope">WorkerGlobalScope</a></code> object, the user agent must run the
following steps:<ol><li><p>If there are no arguments, return without doing
anything. Abort these steps.</li>
<li><p><span title="resolve a url">Resolve</span> each
argument.</li>
<li><p>If any fail, throw a <code>SYNTAX_ERR</code>
exception.</li>
<li>
<p>Attempt to <span>fetch</span> each resource identified by the
resulting <span title="absolute URL">absolute URLs</span>, from
the <span>entry script</span>'s <span>origin</span>, with the
<i>synchronous flag</i> set.</p>
</li>
<li>
<p>For each argument in turn, in the order given, starting with
the first one, run these substeps:</p>
<ol><li>
<p>Wait for the fetching attempt for the corresponding resource
to complete.</p>
<p>If the fetching attempt failed, throw a
<code>NETWORK_ERR</code> exception and abort all these
steps.</p>
<p>If the attempt succeeds, then let <var title="">source</var> be
the script resource <span>decoded as UTF-8, with error
handling</span>.
<a href="#refsHTML">[HTML]</a>
</p>
<p>Let <var title="">language</var> be JavaScript.</p>
<p class="note">As with the worker's script, the script here is
always assumed to be JavaScript, regardless of the MIME
type.</p>
</li>
<li>
<p><span>Create a script</span>, using <var title="">source</var> as the script source and <var title="">language</var> as the scripting language, using the
same global object, browsing context, URL character encoding,
base URL, and script group as the <span title="concept-script">script</span> that was created by the
worker's <a href="#run-a-worker">run a worker</a> algorithm.</p>
<p>Let the newly created <span title="concept-script">script</span> run until it either
returns, fails to parse, fails to catch an exception, or gets
prematurely aborted by the "<a href="#kill-a-worker">kill a worker</a>" or
"<a href="#terminate-a-worker">terminate a worker</a>" algorithms defined above.</p>
<p>If it failed to parse, then throw an ECMAScript
<code>SyntaxError</code> exception and abort all these
steps. <a href="#refsECMA262">[ECMA262]</a></p>
<p>If an exception was raised or if the script was prematurely
aborted, then abort all these steps, letting the exception or
aborting continue to be processed by the script that called the
<code title="dom-WorkerGlobalScope-importScripts"><a href="#dom-workerglobalscope-importscripts">importScripts()</a></code>
method.</p>
<p>If the "<a href="#kill-a-worker">kill a worker</a>" or "<a href="#terminate-a-worker">terminate a
worker</a>" algorithms abort the script then abort all these
steps.</p>
</li>
</ol></li>
</ol><h3 id="the-workernavigator-object"><span class="secno">5.2 </span>The <code><a href="#workernavigator">WorkerNavigator</a></code> object</h3><p>The <dfn id="dom-worker-navigator" title="dom-worker-navigator"><code>navigator</code></dfn> attribute
of the <code><a href="#workerutils">WorkerUtils</a></code> interface must return an instance of
the <code><a href="#workernavigator">WorkerNavigator</a></code> interface, which represents the
identity and state of the user agent (the client):<pre class="idl">interface <dfn id="workernavigator">WorkerNavigator</dfn> {};
<a href="#workernavigator">WorkerNavigator</a> implements <span>NavigatorID</span>;
<a href="#workernavigator">WorkerNavigator</a> implements <span>NavigatorOnLine</span>;</pre><p>Objects implementing the <code><a href="#workernavigator">WorkerNavigator</a></code> interface
also implement the <code>NavigatorID</code> and
<code>NavigatorOnLine</code> interfaces.
<a href="#refsHTML">[HTML]</a>
<p>This <code><a href="#workernavigator">WorkerNavigator</a></code> interface must not exist if the
interface's <span>relevant namespace object</span> is a
<code>Window</code> object. <a href="#refsWEBIDL">[WEBIDL]</a><h3 id="interface-objects-and-constructors"><span class="secno">5.3 </span>Interface objects and constructors</h3><p>There must be no interface objects and constructors available in
the global scope of scripts whose <span>script's global
object</span> is a <code><a href="#workerglobalscope">WorkerGlobalScope</a></code> object except for
the following:<ul><li><p><code>XMLHttpRequest</code> and all interface objects and
constructors defined by the XMLHttpRequest specifications, except
that the <span>document response entity body</span> must always be
null. The <span><code>XMLHttpRequest</code> base URL</span> is the
<span>script's base URL</span>; the
<span><code>XMLHttpRequest</code> origin</span> is the script's
<span>origin</span>. <a href="#refsXHR">[XHR]</a></li>
<li><p>The interface objects and constructors defined by this
specification.</li>
<li><p>Constructors defined by specifications that explicitly say
that they should be visible when the <span>script's global
object</span> is a <code><a href="#dedicatedworkerglobalscope">DedicatedWorkerGlobalScope</a></code>, a
<code><a href="#sharedworkerglobalscope">SharedWorkerGlobalScope</a></code>, or an object implementing the
<code><a href="#workerutils">WorkerUtils</a></code> interface; the interfaces of any objects
with such constructors; and the interfaces of any objects made
accessible through APIs exposed by those constructors or made
accessible through interfaces to be implemented by any objects that
are themselves accessible to scripts whose <span>script's global
object</span> implements the <code><a href="#workerutils">WorkerUtils</a></code>
interface.</li>
</ul><p class="note">These requirements do not override the requirements
defined by the Web IDL specification, in particular concerning the
visibility of interfaces annotated with the <code title="">[NoInterfaceObject]</code> extended attribute.<h3 id="worker-locations"><span class="secno">5.4 </span>Worker locations</h3><pre class="idl">interface <dfn id="workerlocation">WorkerLocation</dfn> {
// <span>URL decomposition IDL attributes</span>
stringifier readonly attribute DOMString <a href="#dom-workerlocation-href" title="dom-WorkerLocation-href">href</a>;
readonly attribute DOMString <a href="#dom-workerlocation-protocol" title="dom-WorkerLocation-protocol">protocol</a>;
readonly attribute DOMString <a href="#dom-workerlocation-host" title="dom-WorkerLocation-host">host</a>;
readonly attribute DOMString <a href="#dom-workerlocation-hostname" title="dom-WorkerLocation-hostname">hostname</a>;
readonly attribute DOMString <a href="#dom-workerlocation-port" title="dom-WorkerLocation-port">port</a>;
readonly attribute DOMString <a href="#dom-workerlocation-pathname" title="dom-WorkerLocation-pathname">pathname</a>;
readonly attribute DOMString <a href="#dom-workerlocation-search" title="dom-WorkerLocation-search">search</a>;
readonly attribute DOMString <a href="#dom-workerlocation-hash" title="dom-WorkerLocation-hash">hash</a>;
};</pre><p>A <code><a href="#workerlocation">WorkerLocation</a></code> object represents an <span>absolute
URL</span> set at its creation.<p>The <dfn id="dom-workerlocation-href" title="dom-WorkerLocation-href"><code>href</code></dfn>
attribute must return the <span>absolute URL</span> that the object
represents.<p>The <code><a href="#workerlocation">WorkerLocation</a></code> interface also has the complement
of <span>URL decomposition IDL attributes</span>, <dfn id="dom-workerlocation-protocol" title="dom-WorkerLocation-protocol"><code>protocol</code></dfn>,
<dfn id="dom-workerlocation-host" title="dom-WorkerLocation-host"><code>host</code></dfn>, <dfn id="dom-workerlocation-port" title="dom-WorkerLocation-port"><code>port</code></dfn>, <dfn id="dom-workerlocation-hostname" title="dom-WorkerLocation-hostname"><code>hostname</code></dfn>,
<dfn id="dom-workerlocation-pathname" title="dom-WorkerLocation-pathname"><code>pathname</code></dfn>,
<dfn id="dom-workerlocation-search" title="dom-WorkerLocation-search"><code>search</code></dfn>,
and <dfn id="dom-workerlocation-hash" title="dom-WorkerLocation-hash"><code>hash</code></dfn>.
These must follow the rules given for <span>URL decomposition IDL
attributes</span>, with the <span title="concept-uda-input">input</span> being the <span>absolute
URL</span> that the object represents (same as the <code title="dom-WorkerLocation-href"><a href="#dom-workerlocation-href">href</a></code> attribute), and the
<span title="concept-uda-setter">common setter action</span> being a
no-op, since the attributes are defined to be readonly.
<a href="#refsHTML">[HTML]</a>
<p>The <code><a href="#workerlocation">WorkerLocation</a></code> interface must not exist if the
interface's <span>relevant namespace object</span> is a
<code>Window</code> object. <a href="#refsWEBIDL">[WEBIDL]</a><h2 class="no-num" id="references">References</h2><p>All references are normative unless marked "Non-normative".</p><dl><dt id="refsDOMCORE">[DOMCORE]</dt>
<dd><cite><a href="http://dvcs.w3.org/hg/domcore/raw-file/tip/Overview.html">Web DOM Core</a></cite>, A. van Kesteren. W3C.</dd>
<dt id="refsDOMEVENTS">[DOMEVENTS]</dt>
<dd><cite><a href="http://dev.w3.org/2006/webapi/DOM-Level-3-Events/html/DOM3-Events.html">Document
Object Model (DOM) Level 3 Events Specification</a></cite>,
D. Schepers. W3C.</dd>
<dt id="refsECMA262">[ECMA262]</dt>
<dd><cite><a href="http://www.ecma-international.org/publications/standards/Ecma-262.htm">ECMAScript
Language Specification</a></cite>. ECMA.</dd>
<dt id="refsHTML">[HTML]</dt>
<dd><cite><a href="http://dev.w3.org/html5/spec/">HTML5</a></cite>, I. Hickson. W3C.
<dt id="refsRFC2119">[RFC2119]</dt>
<dd><cite><a href="http://tools.ietf.org/html/rfc2119">Key words for use in
RFCs to Indicate Requirement Levels</a></cite>, S. Bradner. IETF.</dd>
<dt id="refsWEBIDL">[WEBIDL]</dt>
<dd><cite><a href="http://dev.w3.org/2006/webapi/WebIDL/">Web
IDL</a></cite>, C. McCormack. W3C.</dd>
<dt id="refsXHR">[XHR]</dt>
<dd><cite><a href="http://dev.w3.org/2006/webapi/XMLHttpRequest-2/"><code>XMLHttpRequest</code></a></cite>,
A. van Kesteren. W3C.</dd>
</dl><h2 class="no-num" id="acknowledgements">Acknowledgements</h2><!-- ACKS --><p>Thanks to
Aaron Boodman,
&#1040;&#1083;&#1077;&#1082;&#1089;&#1077;&#1081; &#1055;&#1088;&#1086;&#1089;&#1082;&#1091;&#1088;&#1103;&#1082;&#1086;&#1074; (Alexey Proskuryakov),
Anne van Kesteren,
Ben Turner,
Dmitry Titov,
Drew Wilson,
Jeremy Orlow,
Jonas Sicking,
Justin James,
Kevin Hakanson,
Maciej Stachowiak,
Michael Nordman,
Mike Smith,
and
Philip Taylor
for their useful and substantial comments.<p>Huge thanks to the whole Gears team, who pioneered this
technology and whose experience has been a huge influence on this
specification.