logo by @sawaratsuki1004
React
v19.2
Learn
Reference
Community
Blog

Is this page useful?

في هذه الصفحة

  • Overview
  • Reference
  • <script>
  • Usage
  • Rendering an external script
  • Rendering an inline script

    react@19.2

  • نظرة عامة
  • Hooks
    • useActionState
    • useCallback
    • useContext
    • useDebugValue
    • useDeferredValue
    • useEffect
    • useEffectEvent
    • useId
    • useImperativeHandle
    • useInsertionEffect
    • useLayoutEffect
    • useMemo
    • useOptimistic
    • useReducer
    • useRef
    • useState
    • useSyncExternalStore
    • useTransition
  • المكونات
    • <Fragment> (<>)
    • <Profiler>
    • <StrictMode>
    • <Suspense>
    • <Activity>
    • <ViewTransition> - This feature is available in the latest Canary version of React
  • APIs
    • act
    • addTransitionType - This feature is available in the latest Canary version of React
    • cache
    • cacheSignal
    • captureOwnerStack
    • createContext
    • lazy
    • memo
    • startTransition
    • use
    • experimental_taintObjectReference - This feature is available in the latest Experimental version of React
    • experimental_taintUniqueValue - This feature is available in the latest Experimental version of React
  • react-dom@19.2

  • Hooks
    • useFormStatus
  • المكونات (Components)
    • Common (e.g. <div>)
    • <form>
    • <input>
    • <option>
    • <progress>
    • <select>
    • <textarea>
    • <link>
    • <meta>
    • <script>
    • <style>
    • <title>
  • APIs
    • createPortal
    • flushSync
    • preconnect
    • prefetchDNS
    • preinit
    • preinitModule
    • preload
    • preloadModule
  • Client APIs
    • createRoot
    • hydrateRoot
  • Server APIs
    • renderToPipeableStream
    • renderToReadableStream
    • renderToStaticMarkup
    • renderToString
    • resume
    • resumeToPipeableStream
  • Static APIs
    • prerender
    • prerenderToNodeStream
    • resumeAndPrerender
    • resumeAndPrerenderToNodeStream
  • React Compiler

  • الإعدادات (Configuration)
    • compilationMode
    • gating
    • logger
    • panicThreshold
    • target
  • Directives
    • "use memo"
    • "use no memo"
  • تصريف المكتبات (Compiling Libraries)
  • React DevTools

  • React Performance tracks
  • eslint-plugin-react-hooks

  • Lints
    • exhaustive-deps
    • rules-of-hooks
    • component-hook-factories
    • config
    • error-boundaries
    • gating
    • globals
    • immutability
    • incompatible-library
    • preserve-manual-memoization
    • purity
    • refs
    • set-state-in-effect
    • set-state-in-render
    • static-components
    • unsupported-syntax
    • use-memo
  • قواعد React (Rules of React)

  • نظرة عامة (Overview)
    • Components و Hooks يجب أن تكون Pure
    • React تستدعي Components و Hooks
    • قواعد Hooks
  • React Server Components

  • Server Components
  • Server Functions
  • Directives
    • 'use client'
    • 'use server'
  • Legacy APIs

  • Legacy React APIs
    • Children
    • cloneElement
    • Component
    • createElement
    • createRef
    • forwardRef
    • isValidElement
    • PureComponent
مرجع API
المكونات (Components)

<script>

Canary

React’s extensions to <script> are currently only available in React’s canary and experimental channels. In stable releases of React <script> works only as a built-in browser HTML component. Learn more about React’s release channels here.

The built-in browser <script> component lets you add a script to your document.

<script> alert("hi!") </script>

  • Reference
    • <script>
  • Usage
    • Rendering an external script
    • Rendering an inline script

Reference

<script>

To add inline or external scripts to your document, render the built-in browser <script> component. You can render <script> from any component and React will in certain cases place the corresponding DOM element in the document head and de-duplicate identical scripts.

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

See more examples below.

Props

<script> supports all common element props.

It should have either children or a src prop.

  • children: a string. The source code of an inline script.
  • src: a string. The URL of an external script.

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 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.
  • 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 when using a strict Content Security Policy.
  • referrer: a string. Says what Referer header to send 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.

Props that disable React’s special treatment of scripts:

  • onError: a function. Called when the script fails to load.
  • onLoad: a function. Called when the script finishes being loaded.

Props that are not recommended for use with 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.

Special rendering behavior

React can move <script> components to the document’s <head> and de-duplicate identical scripts.

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.

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.)

Usage

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.

React will de-duplicate scripts that have the same src, inserting only one of them into the DOM even if multiple components render it.

import ShowRenderedHTML from './ShowRenderedHTML.js'; function Map({lat, long}) { return ( <> <script async src="map-api.js" onLoad={() => console.log('script loaded')} /> <div id="map" data-lat={lat} data-long={long} /> </> ); } export default function Page() { return ( <ShowRenderedHTML> <Map /> </ShowRenderedHTML> ); }

ملاحظة

When you want to use a script, it can be beneficial to call the 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.

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>.

import ShowRenderedHTML from './ShowRenderedHTML.js'; function Tracking() { return ( <script> ga('send', 'pageview'); </script> ); } export default function Page() { return ( <ShowRenderedHTML> <h1>My Website</h1> <Tracking /> <p>Welcome</p> </ShowRenderedHTML> ); }
السابق<meta>
التالي<style>

Copyright © Meta Platforms, Inc
no uwu plz
uwu?
Logo by@sawaratsuki1004
تعلم React
بداية سريعة
التثبيت
وصف واجهة المستخدم (UI)
إضافة التفاعلية
إدارة State
مخارج الطوارئ
مرجع API
React APIs
React DOM APIs
المجتمع
ميثاق السلوك
تعرف على الفريق
المساهمون في التوثيق
شكر وتقدير
المزيد
المدونة
React Native
الخصوصية
الشروط
<script> alert("hi!") </script>
<script> alert("hi!") </script>
<script src="script.js" />
Fork
import ShowRenderedHTML from './ShowRenderedHTML.js';

function Map({lat, long}) {
  return (
    <>
      <script async src="map-api.js" onLoad={() => console.log('script loaded')} />
      <div id="map" data-lat={lat} data-long={long} />
    </>
  );
}

export default function Page() {
  return (
    <ShowRenderedHTML>
      <Map />
    </ShowRenderedHTML>
  );
}

Fork
import ShowRenderedHTML from './ShowRenderedHTML.js';

function Tracking() {
  return (
    <script>
      ga('send', 'pageview');
    </script>
  );
}

export default function Page() {
  return (
    <ShowRenderedHTML>
      <h1>My Website</h1>
      <Tracking />
      <p>Welcome</p>
    </ShowRenderedHTML>
  );
}