Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
81 changes: 40 additions & 41 deletions src/content/reference/react-dom/components/script.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
---
script: "<script>"
---

<Intro>

The [built-in browser `<script>` component](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script) lets you add a script to your document.
Встроенный браузерный компонент `<script>` позволяет добавить скрипт в ваш документ.

```js
<script> alert("hi!") </script>
Expand All @@ -16,71 +15,71 @@ The [built-in browser `<script>` component](https://developer.mozilla.org/en-US/

---

## Reference {/*reference*/}
## Справочник {/*reference*/}

### `<script>` {/*script*/}

To add inline or external scripts to your document, render the [built-in browser `<script>` component](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script). You can render `<script>` from any component and React will [in certain cases](#special-rendering-behavior) place the corresponding DOM element in the document head and de-duplicate identical scripts.
Чтобы добавить встроенные или внешние скрипты в ваш документ, используйте встроенный браузерный компонент `<script>`. Вы можете рендерить `<script>` из любого компонента, и React [в некоторых случаях](#special-rendering-behavior) поместит соответствующий DOM-элемент в `<head>` документа и будет дедуплицировать идентичные скрипты.

```js
<script> alert("hi!") </script>
<script src="script.js" />
```

[See more examples below.](#usage)
[См. примеры ниже.](#usage)

#### Props {/*props*/}
#### Пропсы {/*props*/}

`<script>` supports all [common element props.](/reference/react-dom/components/common#props)
`<script>` поддерживает все [общие пропсы элементов.](/reference/react-dom/components/common#props)

It should have *either* `children` or a `src` prop.
Он должен иметь либо `children`, либо пропс `src`.

* `children`: a string. The source code of an inline script.
* `src`: a string. The URL of an external script.
* `children`: строка. Исходный код встроенного скрипта.
* `src`: строка. URL внешнего скрипта.

Other supported props:
Другие поддерживаемые пропсы:

* `async`: a boolean. Allows the browser to defer execution of the script until the rest of the document has been processed — the preferred behavior for performance.
* `crossOrigin`: a string. The [CORS policy](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/crossorigin) to use. Its possible values are `anonymous` and `use-credentials`.
* `fetchPriority`: a string. Lets the browser rank scripts in priority when fetching multiple scripts at the same time. Can be `"high"`, `"low"`, or `"auto"` (the default).
* `integrity`: a string. A cryptographic hash of the script, to [verify its authenticity](https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity).
* `noModule`: a boolean. Disables the script in browsers that support ES modules — allowing for a fallback script for browsers that do not.
* `nonce`: a string. A cryptographic [nonce to allow the resource](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/nonce) when using a strict Content Security Policy.
* `referrer`: a string. Says [what Referer header to send](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#referrerpolicy) when fetching the script and any resources that the script fetches in turn.
* `type`: a string. Says whether the script is a [classic script, ES module, or import map](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script/type).
* `async`: булево значение. Позволяет браузеру отложить выполнение скрипта до тех пор, пока остальная часть документа не будет обработана — это предпочтительное поведение для производительности.
* `crossOrigin`: строка. Используемая [политика CORS](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/crossorigin). Возможные значения: `anonymous` и `use-credentials`.
* `fetchPriority`: строка. Позволяет браузеру определять приоритет скриптов при одновременной загрузке нескольких скриптов. Может быть `"high"`, `"low"` или `"auto"` (по умолчанию).
* `integrity`: строка. Криптографический хеш скрипта для [проверки его подлинности](https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity).
* `noModule`: булево значение. Отключает скрипт в браузерах, поддерживающих ES-модули, позволяя использовать резервный скрипт для браузеров, которые их не поддерживают.
* `nonce`: строка. Криптографический [nonce для разрешения ресурса](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/nonce) при использовании строгой политики безопасности контента (Content Security Policy).
* `referrer`: строка. Указывает, какой [заголовок Referer отправлять](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#referrerpolicy) при загрузке скрипта и любых ресурсов, которые скрипт загружает в свою очередь.
* `type`: строка. Указывает, является ли скрипт [классическим скриптом, ES-модулем или картой импорта](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script/type).

Props that disable React's [special treatment of scripts](#special-rendering-behavior):
Пропсы, отключающие [специальную обработку скриптов React](#special-rendering-behavior):

* `onError`: a function. Called when the script fails to load.
* `onLoad`: a function. Called when the script finishes being loaded.
* `onError`: функция. Вызывается, когда скрипт не удалось загрузить.
* `onLoad`: функция. Вызывается, когда скрипт успешно загружен.

Props that are **not recommended** for use with React:
Пропсы, которые **не рекомендуется** использовать с React:

* `blocking`: a string. If set to `"render"`, instructs the browser not to render the page until the scriptsheet is loaded. React provides more fine-grained control using Suspense.
* `defer`: a string. Prevents the browser from executing the script until the document is done loading. Not compatible with streaming server-rendered components. Use the `async` prop instead.
* `blocking`: строка. Если установлено значение `"render"`, браузеру предписывается не рендерить страницу до тех пор, пока не будет загружен скрипт. React предоставляет более детальный контроль с помощью Suspense.
* `defer`: строка. Предотвращает выполнение скрипта браузером до завершения загрузки документа. Несовместимо со стриминговыми серверно-отрендеренными компонентами. Вместо этого используйте пропс `async`.

#### Special rendering behavior {/*special-rendering-behavior*/}
#### Особое поведение при рендеринге {/*special-rendering-behavior*/}

React can move `<script>` components to the document's `<head>` and de-duplicate identical scripts.
React может перемещать компоненты `<script>` в `<head>` документа и дедуплицировать идентичные скрипты.

To opt into this behavior, provide the `src` and `async={true}` props. React will de-duplicate scripts if they have the same `src`. The `async` prop must be true to allow scripts to be safely moved.
Чтобы использовать это поведение, предоставьте пропсы `src` и `async={true}`. React будет дедуплицировать скрипты, если они имеют одинаковый `src`. Пропс `async` должен быть `true`, чтобы скрипты можно было безопасно перемещать.

This special treatment comes with two caveats:
Эта специальная обработка имеет два нюанса:

* React will ignore changes to props after the script has been rendered. (React will issue a warning in development if this happens.)
* React may leave the script in the DOM even after the component that rendered it has been unmounted. (This has no effect as scripts just execute once when they are inserted into the DOM.)
* React будет игнорировать изменения пропсов после рендеринга скрипта. (В режиме разработки React выдаст предупреждение, если это произойдет.)
* React может оставить скрипт в DOM даже после того, как компонент, который его рендерил, был размонтирован. (Это не имеет значения, так как скрипты выполняются только один раз при вставке в DOM.)

---

## Usage {/*usage*/}
## Использование {/*usage*/}

### Rendering an external script {/*rendering-an-external-script*/}
### Рендеринг внешнего скрипта {/*rendering-an-external-script*/}

If a component depends on certain scripts in order to be displayed correctly, you can render a `<script>` within the component.
However, the component might be committed before the script has finished loading.
You can start depending on the script content once the `load` event is fired e.g. by using the `onLoad` prop.
Если компонент зависит от определенных скриптов для корректного отображения, вы можете рендерить `<script>` внутри компонента.
Однако компонент может быть закоммичен до того, как скрипт завершит загрузку.
Вы можете начать зависеть от содержимого скрипта после срабатывания события `load`, например, используя пропс `onLoad`.

React will de-duplicate scripts that have the same `src`, inserting only one of them into the DOM even if multiple components render it.
React будет дедуплицировать скрипты с одинаковым `src`, вставляя только один из них в DOM, даже если несколько компонентов рендерят его.

<SandpackWithHTMLOutput>

Expand Down Expand Up @@ -108,12 +107,12 @@ export default function Page() {
</SandpackWithHTMLOutput>

<Note>
When you want to use a script, it can be beneficial to call the [preinit](/reference/react-dom/preinit) function. Calling this function may allow the browser to start fetching the script earlier than if you just render a `<script>` component, for example by sending an [HTTP Early Hints response](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/103).
Когда вы хотите использовать скрипт, может быть полезно вызвать функцию [preinit](/reference/react-dom/preinit). Вызов этой функции может позволить браузеру начать загрузку скрипта раньше, чем если бы вы просто рендерили компонент `<script>`, например, отправив ответ [HTTP Early Hints](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/103).
</Note>

### Rendering an inline script {/*rendering-an-inline-script*/}
### Рендеринг встроенного скрипта {/*rendering-an-inline-script*/}

To include an inline script, render the `<script>` component with the script source code as its children. Inline scripts are not de-duplicated or moved to the document `<head>`.
Чтобы включить встроенный скрипт, рендерьте компонент `<script>` с исходным кодом скрипта в качестве его дочерних элементов. Встроенные скрипты не дедуплицируются и не перемещаются в `<head>` документа.

<SandpackWithHTMLOutput>

Expand All @@ -139,4 +138,4 @@ export default function Page() {
}
```

</SandpackWithHTMLOutput>
</SandpackWithHTMLOutput>
Loading