명세 전체 차례
    1. 4.3 스크립팅
      1. 4.3.1 script 요소
        1. 4.3.1.1 스크립트 언어
        2. 4.3.1.2 script 요소의 내용 제한
        3. 4.3.1.3 외부 스크립트에 대한 인라인 문서화
        4. 4.3.1.4 script 요소와 XSLT의 상호작용
      2. 4.3.2 noscript 요소

4.3 스크립팅

스크립트를 통해 문서에 상호작용성을 더할 수 있습니다.

Scripts allow authors to add interactivity to their documents.

가능하다면 스크립팅보다는 선언적인 대체수단을 쓰기를 권장합니다. 선언적인 메커니즘은 종종 더 관리하기 편하고, 많은 사용자가 스크립트를 비활성화하기 때문입니다.

Authors are encouraged to use declarative alternatives to scripting where possible, as declarative mechanisms are often more maintainable, and many users disable scripting.

예를 들어 좀 더 상세한 내용을 다루는 섹션을 감추거나 드러내려 한다면 스크립트 대신 details 요소를 사용할 수 있습니다.

For example, instead of using script to show or hide a section to show more details, the details element could be used.

또한 스크립트 지원이 없을 때를 대비해서 단계적 후퇴가 가능한 애플리케이션을 만들기를 권합니다.

Authors are also encouraged to make their applications degrade gracefully in the absence of scripting support.

예를 들어 테이블 헤더에 동적으로 테이블을 재정렬하는 링크를 제공한다면, 스크립트가 지원되지 않을 때는 그 링크를 통해 재정렬된 테이블을 서버에 요청할 수도 있습니다.

For example, if an author provides a link in a table header to dynamically resort the table, the link could also be made to function without scripts by requesting the sorted table from the server.

4.3.1 script 요소

요소가 속하는 범주Categories
메타데이터.Metadata content.
플로우 컨텐츠Flow content.
구문 컨텐츠Phrasing content.
이 요소가 사용될 수 있는 문맥Contexts in which this element can be used:

메타데이터를 쓸 수 있는 곳

Where metadata content is expected.

구문 컨텐츠를 쓸 수 있는 곳

Where phrasing content is expected.

이 요소가 포함할 수 있는 것Content model:

src 속성이 없다면 type 속성의 값에 따라 다르며 스크립트 내용 제한을 만족해야 합니다.

If there is no src attribute, depends on the value of the type attribute, but must match script content restrictions.

src 속성이 있다면 요소는 반드시 비어 있거나, 비어 있지 않다면 스크립트를 문서화한 내용만을 포함할 수 있습니다. 스크립트를 문서화한 내용은 스크립트 내용 제한을 만족해야 합니다.

If there is a src attribute, the element must be either empty or contain only script documentation that also matches script content restrictions.

요소에 쓸 수 있는 속성Content attributes:
전역 속성Global attributes
src
async
defer
type
charset
DOM 인터페이스DOM interface:
interface HTMLScriptElement : HTMLElement {
           attribute DOMString src;
           attribute boolean async;
           attribute boolean defer;
           attribute DOMString type;
           attribute DOMString charset;
           attribute DOMString text;
};

script 요소를 통해 동적인 스크립트와 데이터 블럭을 문서에 포함시킬 수 있습니다. 이 요소는 사용자에게 어떠한 내용도 나타내지 않습니다.

The script element allows authors to include dynamic script and data blocks in their documents. The element does not represent content for the user.

동적인 스크립트를 인라인으로 포함하거나 src 속성을 통해 외부 파일에서 가져올 수 있습니다. 스크립트 언어가 "text/javascript"가 아니라면 아래에 설명하는 type 속성을 반드시 사용해야 합니다. 무슨 언어를 썼든, script 요소의 내용은 반드시 해당 언어의 명세를 따라야 합니다.

When used to include dynamic scripts, the scripts may either be embedded inline or may be imported from an external file using the src attribute. If the language is not that described by "text/javascript", then the type attribute must be present, as described below. Whatever language is used, the contents of the script element must conform with the requirements of that language's specification.

데이터 블럭(스크립트와는 다릅니다)은 반드시 인라인으로 포함되어야 합니다. 데이터의 포맷은 type 속성으로 명시하며 src 속성을 사용하면 안됩니다. script 요소의 내용은 반드시 해당 포맷에 정의된 요구사항을 만족해야 합니다.

When used to include data blocks (as opposed to scripts), the data must be embedded inline, the format of the data must be given using the type attribute, the src attribute must not be specified, and the contents of the script element must conform to the requirements defined for the format used.

type 속성으로 스크립트 언어 또는 데이터 포맷을 표시합니다. 속성의 값은 유효한 마임 타입이어야 합니다. charset 매개변수를 사용해서는 안 됩니다. 속성이 존재하지 않으면 기본값은 "text/javascript" 입니다.

The type attribute gives the language of the script or format of the data. If the attribute is present, its value must be a valid MIME type. The charset parameter must not be specified. The default, which is used if the attribute is absent, is "text/javascript"

src 속성으로 외부 스크립트 자원의 경로를 제공합니다. 속성의 값은 유효한, 앞뒤로 공백을 허용하고 비어 있지 않은 URL이어야 합니다. type 속성을 사용했다면 그 값이, type 속성을 사용하지 않았다면 "text/javascript"가 자원의 언어입니다. 지정된 자원의 언어가 type 속성에 명시한 것과 일치하고 지정된 자원이 해당 언어의 명세화된 요구사항을 만족한다면 그 자원은 스크립트 자원입니다.

The src attribute, if specified, gives the address of the external script resource to use. The value of the attribute must be a valid non-empty URL potentially surrounded by spaces identifying a script resource of the type given by the type attribute, if the attribute is present, or of the type "text/javascript", if the attribute is absent. A resource is a script resource of a given type if that type identifies a scripting language and the resource conforms with the requirements of that language's specification.

charset 속성은 외부 스크립트 자원의 문자 인코딩을 지정합니다. src 속성을 사용하지 않았다면 이 속성도 사용해선 안 됩니다. charset 속성의 값은 유효한 인코딩 이름이어야 하고 그 인코딩에서 선호하는 마임 이름아스키, 대소문자 구분 없이 일치해야 하며, 외부 자원의 Content-Type 메타데이터가 있다면 Content-Type 메타데이터charset 매개변수와도 일치하여야 합니다. [IANACHARSET]

The charset attribute gives the character encoding of the external script resource. The attribute must not be specified if the src attribute is not present. If the attribute is set, its value must be a valid character encoding name, must be an ASCII case-insensitive match for the preferred MIME name for that encoding, and must match the encoding given in the charset parameter of the Content-Type metadata of the external file, if any. [IANACHARSET]

async, defer 속성은 불리언 속성이며 스크립트가 어떻게 실행될지를 정의합니다. src 속성이 없을 때 defer 속성이나 async 속성을 사용해선 안됩니다.

The async and defer attributes are boolean attributes that indicate how the script should be executed. The defer and async attributes must not be specified if the src attribute is not present.

async 속성과 defer 속성으로 3가지 모드를 선택할 수 있습니다. async 속성이 있다면 스크립트는 가능한 한 즉시 비동기적으로 실행됩니다. async 속성이 없고 defer 속성이 있다면 스크립트는 페이지의 파싱이 완료된 후 실행됩니다. 아무것도 없다면 자원을 가져온 즉시 페이지의 파싱을 멈추고 스크립트를 실행합니다. 역주

There are three possible modes that can be selected using these attributes. If the async attribute is present, then the script will be executed asynchronously, as soon as it is available. If the async attribute is not present but the defer attribute is present, then the script is executed when the page has finished parsing. If neither attribute is present, then the script is fetched and executed immediately, before the user agent continues parsing the page.

이러한 속성 처리의 정확한 상세는(다분히 관습적인 이유로) HTML의 몇 가지 면모를 포함하며 훑어보고 넘길 것은 아닙니다. 따라서 구현에 관한 요구사항은 명세 전반에 걸쳐 분산되어 있습니다. 이 섹션 조금 아래에서 이러한 프로세싱의 핵심 알고리즘을 설명하며 이 알고리즘은 다음 내용과 상호 참조합니다: HTML과 외부 내용에서는 script시작 태그/종료 태그를 파싱하는 규칙, XML에서는 document.write() 메서드의 규칙, 스크립팅 등.

The exact processing details for these attributes are, for mostly historical reasons, somewhat non-trivial, involving a number of aspects of HTML. The implementation requirements are therefore by necessity scattered throughout the specification. The algorithms below (in this section) describe the core of this processing, but these algorithms reference and are referenced by the parsing rules for script start and end tags in HTML, in foreign content, and in XML, the rules for the document.write() method, the handling of scripting, etc.

async 속성을 사용했어도 defer 속성을 사용할 수 있습니다. defer만 지원하는 구형 웹 브라우저가 기본값인 동기적 차단을 하는 대신 defer를 따르게 하기 위함입니다.

The defer attribute may be specified even if the async attribute is specified, to cause legacy Web browsers that only support defer (and not async) to fall back to the defer behavior instead of the synchronous blocking behavior that is the default.

src, type, charset, async, defer 속성을 동적으로 변경해도 직접적인 영향은 전혀 없습니다. 이 속성들은 아래에 설명할 특정한 타이밍에서만 사용됩니다.

Changing the src, type, charset, async, and defer attributes dynamically has no direct effect; these attribute are only used at specific times described below.

A script element has several associated pieces of state.

The first is a flag indicating whether or not the script block has been "already started". Initially, script elements must have this flag unset (script blocks, when created, are not "already started"). When a script element is cloned, the "already started" flag, if set, must be propagated to the clone when it is created.

The second is a flag indicating whether the element was "parser-inserted". Initially, script elements must have this flag unset. It is set by the HTML parser and the XML parser on script elements they insert and affects the processing of those elements.

The third is a flag indicating whether the element will "force-async". Initially, script elements must have this flag set. It is unset by the HTML parser and the XML parser on script elements they insert. In addition, whenever a script element whose "force-async" flag is set has a async content attribute added, the element's "force-async" flag must be unset.

The fourth is a flag indicating whether or not the script block is "ready to be parser-executed". Initially, script elements must have this flag unset (script blocks, when created, are not "ready to be parser-executed"). This flag is used only for elements that are also "parser-inserted", to let the parser know when to execute the script.

The last few pieces of state are the script block's type, the script block's character encoding, and the script block's fallback character encoding. They are determined when the script is prepared, based on the attributes on the element at that time, and the Document of the script element.

When a script element that is not marked as being "parser-inserted" experiences one of the events listed in the following list, the user agent must synchronously prepare the script element:

To prepare a script, the user agent must act as follows:

  1. If the script element is marked as having "already started", then the user agent must abort these steps at this point. The script is not executed.

  2. If the element has its "parser-inserted" flag set, then set was-parser-inserted to true and unset the element's "parser-inserted" flag. Otherwise, set was-parser-inserted to false.

    This is done so that if parser-inserted script elements fail to run when the parser tries to run them, e.g. because they are empty or specify an unsupported scripting language, another script can later mutate them and cause them to run again.

  3. If was-parser-inserted is true and the element does not have an async attribute, then set the element's "force-async" flag to true.

    This is done so that if a parser-inserted script element fails to run when the parser tries to run it, but it is later executed after a script dynamically updates it, it will execute asynchronously even if the async attribute isn't set.

  4. If the element has no src attribute, and its child nodes, if any, consist only of comment nodes and empty text nodes, then the user agent must abort these steps at this point. The script is not executed.

  5. If the element is not in a Document, then the user agent must abort these steps at this point. The script is not executed.

  6. If either:

    • the script element has a type attribute and its value is the empty string, or
    • the script element has no type attribute but it has a language attribute and that attribute's value is the empty string, or
    • the script element has neither a type attribute nor a language attribute, then

    ...let the script block's type for this script element be "text/javascript".

    Otherwise, if the script element has a type attribute, let the script block's type for this script element be the value of that attribute with any leading or trailing sequences of space characters removed.

    Otherwise, the element has a non-empty language attribute; let the script block's type for this script element be the concatenation of the string "text/" followed by the value of the language attribute.

    The language attribute is never conforming, and is always ignored if there is a type attribute present.

  7. If the user agent does not support the scripting language given by the script block's type for this script element, then the user agent must abort these steps at this point. The script is not executed.

  8. If was-parser-inserted is true, then flag the element as "parser-inserted" again, and set the element's "force-async" flag to false.

  9. The user agent must set the element's "already started" flag.

    The state of the element at this moment is later used to determine the script source.

  10. If the element is flagged as "parser-inserted", but the element's Document is not the Document of the parser that created the element, then abort these steps.

  11. If scripting is disabled for the script element, then the user agent must abort these steps at this point. The script is not executed.

    The definition of scripting is disabled means that, amongst others, the following scripts will not execute: scripts in XMLHttpRequest's responseXML documents, scripts in DOMParser-created documents, scripts in documents created by XSLTProcessor's transformToDocument feature, and scripts that are first inserted by a script into a Document that was created using the createDocument() API. [XHR] [DOMPARSER] [DOMCORE]

  12. If the script element has an event attribute and a for attribute, then run these substeps:

    1. Let for be the value of the for attribute.

    2. Let event be the value of the event attribute.

    3. Strip leading and trailing whitespace from event and for.

    4. If for is not an ASCII case-insensitive match for the string "window", then the user agent must abort these steps at this point. The script is not executed.

    5. If event is not an ASCII case-insensitive match for either the string "onload" or the string "onload()", then the user agent must abort these steps at this point. The script is not executed.

  13. If the script element has a charset attribute, then let the script block's character encoding for this script element be the encoding given by the charset attribute.

    Otherwise, let the script block's fallback character encoding for this script element be the same as the encoding of the document itself.

    Only one of these two pieces of state is set.

  14. If the element has a src attribute whose value is not the empty string, then the value of that attribute must be resolved relative to the element, and if that is successful, the specified resource must then be fetched, from the origin of the element's Document.

    If the src attribute's value is the empty string or if it could not be resolved, then the user agent must queue a task to fire a simple event named error at the element, and abort these steps.

    For historical reasons, if the URL is a javascript: URL, then the user agent must not, despite the requirements in the definition of the fetching algorithm, actually execute the script in the URL; instead the user agent must act as if it had received an empty HTTP 400 response.

    For performance reasons, user agents may start fetching the script as soon as the attribute is set, instead, in the hope that the element will be inserted into the document. Either way, once the element is inserted into the document, the load must have started. If the UA performs such prefetching, but the element is never inserted in the document, or the src attribute is dynamically changed, then the user agent will not execute the script, and the fetching process will have been effectively wasted.

  15. Then, the first of the following options that describes the situation must be followed:

    If the element has a src attribute, and the element has a defer attribute, and the element has been flagged as "parser-inserted", and the element does not have an async attribute

    The element must be added to the end of the list of scripts that will execute when the document has finished parsing associated with the Document of the parser that created the element.

    The task that the networking task source places on the task queue once the fetching algorithm has completed must set the element's "ready to be parser-executed" flag. The parser will handle executing the script.

    If the element has a src attribute, and the element has been flagged as "parser-inserted", and the element does not have an async attribute

    The element is the pending parsing-blocking script of the Document of the parser that created the element. (There can only be one such script per Document at a time.)

    The task that the networking task source places on the task queue once the fetching algorithm has completed must set the element's "ready to be parser-executed" flag. The parser will handle executing the script.

    If the element does not have a src attribute, and the element has been flagged as "parser-inserted", and the Document of the HTML parser or XML parser that created the script element has a style sheet that is blocking scripts

    The element is the pending parsing-blocking script of the Document of the parser that created the element. (There can only be one such script per Document at a time.)

    Set the element's "ready to be parser-executed" flag. The parser will handle executing the script.

    If the element has a src attribute, does not have an async attribute, and does not have the "force-async" flag set

    The element must be added to the end of the list of scripts that will execute in order as soon as possible associated with the Document of the script element at the time the prepare a script algorithm started.

    The task that the networking task source places on the task queue once the fetching algorithm has completed must run the following steps:

    1. If the element is not now the first element in the list of scripts that will execute in order as soon as possible to which it was added above, then mark the element as ready but abort these steps without executing the script yet.

    2. Execution: Execute the script block corresponding to the first script element in this list of scripts that will execute in order as soon as possible.

    3. Remove the first element from this list of scripts that will execute in order as soon as possible.

    4. If this list of scripts that will execute in order as soon as possible is still not empty and the first entry has already been marked as ready, then jump back to the step labeled execution.

    If the element has a src attribute

    The element must be added to the set of scripts that will execute as soon as possible of the Document of the script element at the time the prepare a script algorithm started.

    The task that the networking task source places on the task queue once the fetching algorithm has completed must execute the script block and then remove the element from the set of scripts that will execute as soon as possible.

    Otherwise
    The user agent must immediately execute the script block, even if other scripts are already executing.

Fetching an external script must delay the load event of the element's document until the task that is queued by the networking task source once the resource has been fetched (defined above) has been run.

The pending parsing-blocking script of a Document is used by the Document's parser(s).

If a script element that blocks a parser gets moved to another Document before it would normally have stopped blocking that parser, it nonetheless continues blocking that parser until the condition that causes it to be blocking the parser no longer applies (e.g. if the script is a pending parsing-blocking script because there was a style sheet that is blocking scripts when it was parsed, but then the script is moved to another Document before the style sheet loads, the script still blocks the parser until the style sheets are all loaded, at which time the script executes and the parser is unblocked).

When the user agent is required to execute a script block, it must run the following steps:

  1. If the element is flagged as "parser-inserted", but the element's Document is not the Document of the parser that created the element, then abort these steps.

  2. Jump to the appropriate set of steps from the list below:

    If the load resulted in an error (for example a DNS error, or an HTTP 404 error)

    Executing the script block must just consist of firing a simple event named error at the element.

    If the load was successful

    Executing the script block must consist of running the following steps. For the purposes of these steps, the script is considered to be from an external file if, while the prepare a script algorithm above was running for this script, the script element had a src attribute specified.

    1. Initialize the script block's source as follows:

      If the script is from an external file and the script block's type is a text-based language

      The contents of that file, interpreted as string of Unicode characters, are the script source.

      To obtain the string of Unicode characters, the user agent run the following steps:

      1. If the resource's Content Type metadata, if any, specifies a character encoding, and the user agent supports that encoding, then let character encoding be that encoding, and jump to the bottom step in this series of steps.

      2. If the algorithm above set the script block's character encoding, then let character encoding be that encoding, and jump to the bottom step in this series of steps.

      3. For each of the rows in the following table, starting with the first one and going down, if the file has as many or more bytes available than the number of bytes in the first column, and the first bytes of the file match the bytes given in the first column, then set character encoding to the encoding given in the cell in the second column of that row, and jump to the bottom step in this series of steps:

        Bytes in Hexadecimal Encoding
        FE FF Big-endian UTF-16
        FF FE Little-endian UTF-16
        EF BB BF UTF-8

        This step looks for Unicode Byte Order Marks (BOMs).

      4. Let character encoding be the script block's fallback character encoding.

      5. Convert the file to Unicode using character encoding, following the rules for doing so given by the specification for the script block's type.

      If the script is from an external file and the script block's type is an XML-based language

      The external file is the script source. When it is later executed, it must be interpreted in a manner consistent with the specification defining the language given by the script block's type.

      If the script is inline and the script block's type is a text-based language

      The value of the text IDL attribute at the time the element's "already started" flag was last set is the script source.

      If the script is inline and the script block's type is an XML-based language

      The child nodes of the script element at the time the element's "already started" flag was last set are the script source.

    2. If the script is from an external file, then increment the ignore-destructive-writes counter of the script element's Document. Let neutralized doc be that Document.

    3. Create a script from the script element node, using the script block's source and the script block's type.

      This is where the script is compiled and actually executed.

    4. Decrement the ignore-destructive-writes counter of neutralized doc, if it was incremented in the earlier step.

    5. If the script is from an external file, fire a simple event named load at the script element.

      Otherwise, the script is internal; queue a task to fire a simple event named load at the script element.

The IDL attributes src, type, charset, and defer, each must reflect the respective content attributes of the same name.

The async IDL attribute controls whether the element will execute asynchronously or not. If the element's "force-async" flag is set, then, on getting, the async IDL attribute must return true, and on setting, the "force-async" flag must first be unset, and then the content attribute must be removed if the IDL attribute's new value is false, and must be set to the empty string if the IDL attribute's new value is true. If the element's "force-async" flag is not set, the IDL attribute must reflect the async content attribute.

script . text [ = value ]

요소의 내용을 반환하되 텍스트 노드가 아닌 자식 노드는 제외합니다.

Returns the contents of the element, ignoring child nodes that aren't text nodes.

요소의 자식 요소를 대체하기 위해 사용할 수 있습니다.

Can be set, to replace the element's children with the given value.

The IDL attribute text must return a concatenation of the contents of all the text nodes that are direct children of the script element (ignoring any other nodes such as comments or elements), in tree order. On setting, it must act the same way as the textContent IDL attribute.

document.write() 메서드를 통해 삽입된 script 요소는 실행(대개 동기적으로)되지만, innerHTML 속성이나 outerHTML 속성을 통해 삽입된 스크립트는 전혀 실행되지 않습니다.

When inserted using the document.write() method, script elements execute (typically synchronously), but when inserted using innerHTML and outerHTML attributes, they do not execute at all.

이 예제에는 두 개의 script 요소를 사용했습니다. 하나는 외부 스크립트이고 다른 하나는 데이터를 약간 포함합니다.

In this example, two script elements are used. One embeds an external script, and the other includes some data.

<script src="game-engine.js"></script>
<script type="text/x-game-map">
........U.........e
o............A....e
.....A.....AAA....e
.A..AAA...AAAAA...e
</script>

이 예제의 데이터는 비디오 게임의 맵을 생성하는데 썼을 법 하지만, 데이터를 꼭 그러한 방법으로 사용해야만 하는 건 아닙니다. 어쩌면 게임의 맵은 페이지의 다른 마크업을 통해 삽입했고 예제의 맵은 사용자들의 검색 편의를 위해 제공한 것일 수도 있습니다.

The data in this case might be used by the script to generate the map of a video game. The data doesn't have to be used that way, though; maybe the map data is actually embedded in other parts of the page's markup, and the data block here is just used by the site's search engine to help users who are looking for particular features in their game maps.

다음 샘플은 script 요소가 문서의 다른 부분에서 사용될 함수를 어떻게 정의하는지 보여줍니다. 문서를 파싱하는 도중에 script 요소로 스크립트를 실행한 것도 눈여겨 보십시오. 파싱한 도중에 실행한 스크립트는 폼의 출력을 초기화합니다.

The following sample shows how a script element can be used to define a function that is then used by other parts of the document. It also shows how a script element can be used to invoke script while the document is being parsed, in this case to initialize the form's output.

<script>
 function calculate(form) {
   var price = 52000;
   if (form.elements.brakes.checked)
     price += 1000;
   if (form.elements.radio.checked)
     price += 2500;
   if (form.elements.turbo.checked)
     price += 5000;
   if (form.elements.sticker.checked)
     price += 250;
   form.elements.result.value = price;
 }
</script>
<form name="pricecalc" onsubmit="return false" onchange="calculate(this)">
 <fieldset>
  <legend>Work out the price of your car</legend>
  <p>Base cost: £52000.</p>
  <p>Select additional options:</p>
  <ul>
   <li><label><input type=checkbox name=brakes> Ceramic brakes (£1000)</label></li>
   <li><label><input type=checkbox name=radio> Satellite radio (£2500)</label></li>
   <li><label><input type=checkbox name=turbo> Turbo charger (£5000)</label></li>
   <li><label><input type=checkbox name=sticker> "XZ" sticker (£250)</label></li>
  </ul>
  <p>Total: £<output name=result></output></p>
 </fieldset>
 <script>
  calculate(document.forms.pricecalc);
 </script>
</form>
4.3.1.1 스크립트 언어

A user agent is said to support the scripting language if the script block's type is an ASCII case-insensitive match for the MIME type string of a scripting language that the user agent implements.

다음은 몇 가지 마임 타입 문자열과 그것이 참조하는 언어의 목록입니다.

The following lists some MIME type strings and the languages to which they refer:

"application/ecmascript"
"application/javascript"
"application/x-ecmascript"
"application/x-javascript"
"text/ecmascript"
"text/javascript"
"text/javascript1.0"
"text/javascript1.1"
"text/javascript1.2"
"text/javascript1.3"
"text/javascript1.4"
"text/javascript1.5"
"text/jscript"
"text/livescript"
"text/x-ecmascript"
"text/x-javascript"
JavaScript. [ECMA262]
"text/javascript;e4x=1"
JavaScript with ECMAScript for XML. [ECMA357]

User agents may support other MIME types and other languages.

When examining types to determine if they support the language, user agents must not ignore unknown MIME parameters — types with unknown parameters must be assumed to be unsupported. The charset parameter must be treated as an unknown parameter for the purpose of comparing MIME types here.

4.3.1.2 Restrictions for contents of script elements

script 요소의 textContent는 다음의 ABNF, 유니코드를 위한 문자셋의 script 결과와 일치하여야 합니다. [ABNF]

The textContent of a script element must match the script production in the following ABNF, the character set for which is Unicode. [ABNF]

script        = data1 *( escape [ script-start data3 ] "-->" data1 ) [ escape ]
escape        = "<!--" data2 *( script-start data3 script-end data2 )

data1         = <any string that doesn't contain a substring that matches not-data1>
not-data1     = "<!--"

data2         = <any string that doesn't contain a substring that matches not-data2>
not-data2     = script-start / "-->"

data3         = <any string that doesn't contain a substring that matches not-data3>
not-data3     = script-end / "-->"

script-start  = lt       s c r i p t tag-end
script-end    = lt slash s c r i p t tag-end

lt            =  %x003C ; U+003C LESS-THAN SIGN character (<)
slash         =  %x002F ; U+002F SOLIDUS character (/)

s             =  %x0053 ; U+0053 LATIN CAPITAL LETTER S
s             =/ %x0073 ; U+0073 LATIN SMALL LETTER S
c             =  %x0043 ; U+0043 LATIN CAPITAL LETTER C
c             =/ %x0063 ; U+0063 LATIN SMALL LETTER C
r             =  %x0052 ; U+0052 LATIN CAPITAL LETTER R
r             =/ %x0072 ; U+0072 LATIN SMALL LETTER R
i             =  %x0049 ; U+0049 LATIN CAPITAL LETTER I
i             =/ %x0069 ; U+0069 LATIN SMALL LETTER I
p             =  %x0050 ; U+0050 LATIN CAPITAL LETTER P
p             =/ %x0070 ; U+0070 LATIN SMALL LETTER P
t             =  %x0054 ; U+0054 LATIN CAPITAL LETTER T
t             =/ %x0074 ; U+0074 LATIN SMALL LETTER T

tag-end       =  %x0009 ; U+0009 CHARACTER TABULATION (tab)
tag-end       =/ %x000A ; U+000A LINE FEED (LF)
tag-end       =/ %x000C ; U+000C FORM FEED (FF)
tag-end       =/ %x0020 ; U+0020 SPACE
tag-end       =/ %x002F ; U+002F SOLIDUS (/)
tag-end       =/ %x003E ; U+003E GREATER-THAN SIGN (>)

script 요소에 문서로 만들어진 내용이 들어있다면 해당 내용에 대해서는 조금 더 상세한 제한 사항이 있습니다. 다음 섹션에서 설명합니다.

When a script element contains script documentation, there are further restrictions on the contents of the element, as described in the section below.

4.3.1.3 Inline documentation for external scripts

script 요소에 src 속성이 있으면 요소의 내용은 스크립트에 대한 주석이므로 IDL 속성 text의 값과 다음 ABNF documentation 결과가 일치해야 합니다. [ABNF] 역주

If a script element's src attribute is specified, then the contents of the script element, if any, must be such that the value of the text IDL attribute, which is derived from the element's contents, matches the documentation production in the following ABNF, the character set for which is Unicode. [ABNF]

documentation = *( *( space / tab / comment ) [ line-comment ] newline )
comment       = slash star *( not-star / star not-slash ) 1*star slash
line-comment  = slash slash *not-newline

; characters
tab           = %x0009 ; U+0009 CHARACTER TABULATION (tab)
newline       = %x000A ; U+000A LINE FEED (LF)
space         = %x0020 ; U+0020 SPACE
star          = %x002A ; U+002A ASTERISK (*)
slash         = %x002F ; U+002F SOLIDUS (/)
not-newline   = %x0000-0009 / %x000B-10FFFF
                ; a Unicode character other than U+000A LINE FEED (LF)
not-star      = %x0000-0029 / %x002B-10FFFF
                ; a Unicode character other than U+002A ASTERISK (*)
not-slash     = %x0000-002E / %x0030-10FFFF
                ; a Unicode character other than U+002F SOLIDUS (/)

요소의 내용을 자바스크립트 주석에 적어두는 것과 마찬가지입니다.

This corresponds to putting the contents of the element in JavaScript comments.

이러한 요구사항은 앞서 script 요소의 내용에 대한 제한사항에 더해지는 것입니다.

This requirement is in addition to the earlier restrictions on the syntax of contents of script elements.

이것을 통해 스크립트 자체는 외부 파일에서 참조하면서도 스크립트의 문서화된 내용, 예를 들어 라이센스 정보라든가 API 정보 같은 것들을 문서 본문에 포함할 수 있습니다. 이러한 문법은 저자들이 src 속성을 사용하면서도, 실수로 유효한 스크립트처럼 보이는 내용을 포함하는 것을 방지할 것입니다.역주

This allows authors to include documentation, such as license information or API information, inside their documents while still referring to external script files. The syntax is constrained so that authors don't accidentally include what looks like valid script while also providing a src attribute.

<script src="cool-effects.js">
 // create new instances using:
 //    var e = new Effect();
 // start the effect using .play, stop using .stop:
 //    e.play();
 //    e.stop();
</script>
4.3.1.4 Interaction of script elements and XSLT

This section is non-normative.

This specification does not define how XSLT interacts with the script element (or, indeed, how XSLT processing triggers the stop parsing steps, how it interacts with the navigation algorithm, or how it fits in with the event loop). However, in the absence of another specification actually defining this, here are some guidelines for implementors, based on existing implementations:

The main distinction between the first two cases and the last case is that the first two operate on Documents and the last operates on a fragment.

4.3.2 The noscript element

요소가 속하는 범주Categories
메타데이터.Metadata content.
플로우 컨텐츠Flow content.
구문 컨텐츠Phrasing content.
이 요소가 사용될 수 있는 문맥Contexts in which this element can be used:

HTML 문서head 요소 내부. 단, noscript 요소 내부는 안됩니다.

In a head element of an HTML document, if there are no ancestor noscript elements.

HTML 문서에서 구문 컨텐츠가 나타날 수 있는 곳. 단, noscript 요소 내부는 안됩니다.

Where phrasing content is expected in HTML documents, if there are no ancestor noscript elements.

이 요소가 포함할 수 있는 것Content model:

스크립팅이 비활성화되었을 때 head 요소 내부에 있으면: link, style, meta 요소를 순서나 개수에 무관하게 포함할 수 있습니다.

When scripting is disabled, in a head element: in any order, zero or more link elements, zero or more style elements, and zero or more meta elements.

스크립팅이 비활성화되었을 때 head 요소 내부에 없으면: 투명한 요소. 하지만, noscript 요소는 포함할 수 없습니다.

When scripting is disabled, not in a head element: transparent, but there must be no noscript element descendants.

그렇지 않으면: 아래에서 주어진 요구사항을 만족하는 텍스트를 포함할 수 있습니다.

Otherwise: text that conforms to the requirements given in the prose.

요소에 쓸 수 있는 속성Content attributes:
전역 속성Global attributes
DOM 인터페이스DOM interface:
Uses HTMLElement.

noscript 요소는 스크립트가 활성화되었을 때는 아무것도 나타내지 않습니다. 스크립트가 비활성화되었을 때만 자신의 자식 요소들을 나타냅니다. 이것은 문서의 파싱 방법에 영향을 미침으로써, 스크립트를 지원하는 사용자 에이전트와 그렇지 않은 사용자 에이전트에게 서로 다른 마크업을 제공하기 위해 사용합니다.

The noscript element represents nothing if scripting is enabled, and represents its children if scripting is disabled. It is used to present different markup to user agents that support scripting and those that don't support scripting, by affecting how the document is parsed.

HTML 문서에 사용되었을 때, 가능한 내용 모델은 다음과 같습니다.

When used in HTML documents, the allowed content model is as follows:

스크립트가 비활성화되어있을 때 head 요소 안에 있는 noscript 요소

In a head element, if scripting is disabled for the noscript element

noscript 요소는 link, style, meta 요소만 가질 수 있습니다.

The noscript element must contain only link, style, and meta elements.

스크립트가 활성화되어있을 때 head 요소 안에 있는 noscript 요소

In a head element, if scripting is enabled for the noscript element

요소는 텍스트만 가질 수 있습니다. 단, 요소를 context로 간주하고 그 내용을 input으로 간주하여 HTML 파싱 알고리즘을 활성화한 결과가 link, style, meta 만으로 구성된 노드의 목록을 반환하며 그것이 noscript 요소의 자식으로 포함되었을 때 요구사항에 맞고, 또한 파싱 에러를 일으키지 않는 때는 예외입니다.

The noscript element must contain only text, except that invoking the HTML fragment parsing algorithm with the noscript element as the context element and the text contents as the input must result in a list of nodes that consists only of link, style, and meta elements that would be conforming if they were children of the noscript element, and no parse errors.

스크립트가 비활성화되어있을 때 head 요소 밖에 있는 noscript 요소

Outside of head elements, if scripting is disabled for the noscript element

요소의 내용 모델은 투명합니다. 또한, 요소는 noscript 요소를 조상 요소로서 가질 수 없습니다.(즉, 중첩될 수 없습니다.)

The noscript element's content model is transparent, with the additional restriction that a noscript element must not have a noscript element as an ancestor (that is, noscript can't be nested).

스크립트가 활성화되어있을 때 head 요소 밖에 있는 noscript 요소

Outside of head elements, if scripting is enabled for the noscript element

요소는 텍스트만 가질 수 있습니다. 다음의 알고리즘을 실행한 결과가 noscript, script 요소를 갖지 않는 올바른 문서가 되고, 또한 알고리즘을 실행하는 과정에서 파싱 에러를 반환하지 않아야 합니다.

The noscript element must contain only text, except that the text must be such that running the following algorithm results in a conforming document with no noscript elements and no script elements, and such that no step in the algorithm causes an HTML parser to flag a parse error:

  1. 문서에서 모든 script 요소를 제거합니다.

    Remove every script element from the document.

  2. 문서에서 모든 noscript 요소의 목록을 만듭니다. 각 noscript 요소에 대해 다음 단계를 수행합니다.

    Make a list of every noscript element in the document. For every noscript element in that list, perform the following steps:

    1. noscript 요소의 부모 요소를 parent element라 칭합니다.

      Let the parent element be the parent element of the noscript element.

    2. parent element의 모든 자식 요소 중 noscript 요소의 앞에 있는 것을 취하고 이것을 the before children라 칭합니다.

      Take all the children of the parent element that come before the noscript element, and call these elements the before children.

    3. parent element의 모든 자식 요소 중 noscript 요소의 뒤에 있는 것을 취하고 이것을 the after children라 칭합니다.

      Take all the children of the parent element that come after the noscript element, and call these elements the after children.

    4. noscript 요소의 모든 텍스트 노드를 연결하고 이것을 s라 칭합니다.

      Let s be the concatenation of all the text node children of the noscript element.

    5. parent elementinnerHTMLs가 되도록 합니다(noscript 요소가 문서에서 제거되는 부수효과가 있습니다).

      Set the innerHTML attribute of the parent element to the value of s. (This, as a side-effect, causes the noscript element to be removed from the document.)

    6. the before childrenparent element의 앞에 배치합니다. 순서는 그대로 유지합니다.

      Insert the before children at the start of the parent element, preserving their original relative order.

    7. the after childrenparent element의 뒤에 배치합니다. 순서는 그대로 유지합니다.

      Insert the after children at the end of the parent element, preserving their original relative order.

이러한 모든 변형은 HTML 파서가 실행될 때 스크립트가 활성화되었는가에 따라 noscript 요소를 다르게 처리하기 때문입니다.

All these contortions are required because, for historical reasons, the noscript element is handled differently by the HTML parser based on whether scripting was enabled or not when the parser was invoked.

noscript 요소는 XML 문서에서 사용될 수 없습니다.

The noscript element must not be used in XML documents.

noscript 요소는 HTML 문법에서만 의미가 있습니다. XHTML 문법에서는 아무런 효과도 없습니다.

The noscript element is only effective in the HTML syntax, it has no effect in the XHTML syntax.

The noscript element has no other requirements. In particular, children of the noscript element are not exempt from form submission, scripting, and so forth, even when scripting is enabled for the element.

다음의 예제는 noscript 요소를 스크립트에 대한 폴백으로 사용했습니다.

In the following example, a noscript element is used to provide fallback for a script.

<form action="calcSquare.php">
 <p>
  <label for=x>Number</label>:
  <input id="x" name="x" type="number">
 </p>
 <script>
  var x = document.getElementById('x');
  var output = document.createElement('p');
  output.textContent = 'Type a number; it will be squared right then!';
  x.form.appendChild(output);
  x.form.onsubmit = function () { return false; }
  x.oninput = function () {
    var v = x.valueAsNumber;
    output.textContent = v + ' squared is ' + v * v;
  };
 </script>
 <noscript>
  <input type=submit value="Calculate Square">
 </noscript>
</form>

스크립트가 비활성화되면 계산 결과를 서버에서 받아 오는 버튼이 나타납니다. 스크립트가 활성화되어 있다면 값은 즉시 계산됩니다.

When script is disabled, a button appears to do the calculation on the server side. When script is enabled, the value is computed on-the-fly instead.

noscript 요소는 무딘 도구입니다. 이따금 스크립트가 활성화되었는데도 뭔가 이유가 있어 페이지의 스크립트가 실패할 때도 있습니다. 따라서 noscript 요소의 사용을 피하는 것이 좋습니다. 대신 스크립트를 써서 스크립트 없는 페이지를 즉석에서 스크립트 있는 페이지로 변경하는 편이 더 좋습니다. 다음 예제를 참고하십시오.

The noscript element is a blunt instrument. Sometimes, scripts might be enabled, but for some reason the page's script might fail. For this reason, it's generally better to avoid using noscript, and to instead design the script to change the page from being a scriptless page to a scripted page on the fly, as in the next example:

<form action="calcSquare.php">
 <p>
  <label for=x>Number</label>:
  <input id="x" name="x" type="number">
 </p>
 <input id="submit" type=submit value="Calculate Square">
 <script>
  var x = document.getElementById('x');
  var output = document.createElement('p');
  output.textContent = 'Type a number; it will be squared right then!';
  x.form.appendChild(output);
  x.form.onsubmit = function () { return false; }
  x.oninput = function () {
    var v = x.valueAsNumber;
    output.textContent = v + ' squared is ' + v * v;
  };
  var submit = document.getElementById('submit');
  submit.parentNode.removeChild(submit);
 </script>
</form>

위와 같은 테크닉은 XHTML에서도 유용합니다. XHTML 문법에서는 noscript 요소가 지원되지 않기 때문입니다.

The above technique is also useful in XHTML, since noscript is not supported in the XHTML syntax.

이 문장을 이해하려면 자바스크립트의 배타적 속성을 이해해야 합니다. 브라우저에서 문서를 파싱하다가 스크립트 블럭을 만났을 때, 스크립트를 실행하지 않고서는 이 스크립트가 페이지에 어떤 영향을 미칠 지 알 수 없으므로 다른 모든 작업을 중지하고 스크립트를 먼저 내려받아서 실행해야 합니다. 이미지나 스타일시트 등을 내려받던 것도 모두 멈춥니다.

defer 속성의 정확한 의미는 "이 스크립트를 실행해도 페이지 내용이 바뀌지는 않으니까 아무때나 실행해도 된다"는 뜻입니다. 이 속성을 지원하는 브라우저(인터넷 익스플로러와 파이어폭스 밖에 없습니다)는 스크립트를 내려받기는 하되, 이미지 등 다른 요소도 병렬로 내려받고 페이지 파싱까지 마친 후 스크립트를 실행합니다. 개인적으로는, defer 속성을 쓰는 것과 <body> 바로 앞에 스크립트를 두는 것 사이에 의미 있는 차이가 있는지 잘 이해하지 못하겠습니다. 돌아가기

ABNF 표현을 자세히 보면 자바스크립트 주석과 마찬가지 형식을 쓰게끔 강제한 것을 알 수 있습니다. //이 한 줄 주석, /* */가 여러 줄 주석이라고 설명했습니다. 즉, <script> 요소 안에 뭔가 쓴다면 항상 자바스크립트 주석의 형식을 지켜야 유효성 검사를 통과하게끔 강제하는 겁니다. 이렇게 강제하는 이유는 저작 시간을 낭비하게 하는 에러들을 방지하기 위해서입니다. 돌아가기

이 내용에 대해서는 앞 장에 더 상세한 설명이 있습니다. 링크로 이동한 후 맨 아래 근처, "저작 시간을 낭비하게 하는 에러들"을 읽어보십시오.돌아가기