> For AI agents: the complete documentation index is available at /next/llms.txt, the full documentation bundle is available at /next/llms-full.txt.

# lynx: requestResourcePrefetch() static method

APISummary
- This API is used for proactively initiating the preloading of CDN resources from the frontend, currently supporting **image**, **video**, **audio**, and **font** resource types.
- The preloaded resources will not be returned to the frontend through this API; instead, they are retained in memory or on disk. Therefore, after preloading is complete, a `unique key` is needed to specify the resource to the component:
  - The key for an image resource is consistent with the `uri` parameter during its preloading. When rendering, pass this key to the [src](/next/api/elements/built-in/image.md#src) attribute of the `<image />` component, allowing the component to locate the resource.

## Syntax

```ts
requestResourcePrefetch(
  data: object,
  callback: (res: object) => void,
  config?: {
    awaitComplete?: boolean;
    awaitTimeout?: number; // ms, default is 60000
  }
) : void;
```

### Parameters

#### `data`

A collection that describes all the details of the resources to be preloaded, its keys are defined as follows:

- `data`: Type `array`, each item inside the array corresponds to a resource. The keys for each item are defined as follows:
  - `uri`: Type `string`, represents the CDN address of the resource.
  - `type`: Type `string`, represents the type of resource. The defined types of resources are as follows:
    - `image`: Image resource. (api/elements/built-in/image.html#trailnewimage--) switch for the Image component to preload images.)
    - `video`: Video resource.
    - `audio`: Audio resource.
    - `font`: Font resource.
  - `params` (optional): Custom control parameters for resource preloading, the supported parameters are as follows:
    - `priority` (optional): Only for `image` type resources. Indicates network request priority. If the priority is high, other image requests will be blocked while the image library preloads these images, which may slow down the display of other images. Therefore, if these preloaded images are not immediately needed for display, consider setting a lower priority. The options supported are as follows:
      - `high`: High priority.
      - `medium`: Medium priority.
      - `low`: Low priority, this is the default value.
    - `cacheTarget` (optional): Only for `image` type resources. Indicates the form in which resources are saved. The options supported are as follows:
      - `disk`: Resource is saved to disk after preloading is completed, this is the default value.
      - `bitmap`: Resource is decoded into a bitmap and saved in memory after preloading. (**Note: Currently, Android bitmap caching is not yet effective.**)
    - `preloadKey`: Only for `video`, `audio` type resources. Represents a unique key that identifies the resource. When rendering the \<x-video-pro> component, this key must be specified so that the component can find the preloaded cache. This is a required parameter.
    - `size` (optional): Only for `video` type resources. Indicates the size of the preload, with a default value of 500 \* 1024 (bytes).

#### `callback`

The callback function called after the API is executed or fails. The inside definition of its parameters is as follows:

- `code`: Type `number`, status code, which may take the following values:
  - `0`: Success.
  - `32101`: Parameter error.
  - `32102`: Image prefetch helper does not exist.
  - `32103`: Resource service does not exist.
  - `32104`: Timed out while waiting for prefetch completion. This is only possible when `config.awaitComplete = true`.
- `msg`: Type `string`, a global error message.
- `details`: Type `array`, where each detail represents the preload status details of a resource, with the internal definition of detail as follows:
  - `code`: Type `number`, status code, which may take the following values:
    - `0`: Success.
    - `32101`: Parameter error.
    - `32102`: Image prefetch helper does not exist.
    - `32103`: Resource service does not exist.
  - `msg`: Type `string`, error message.
  - `uri`: Type `string`, represents the CDN address of the resource.
  - `type`: Type `string`, represents the type of the resource, with resource types defined as follows:
    - `image`: Image resource.
    - `video`: Video resource.
    - `audio`: Audio resource.
    - `font`: Font resource.

#### `config` (since 3.9)

Controls whether the callback waits for prefetch completion and how long it waits:

- `awaitComplete` (optional): Type `boolean`, default `false`. When set to `true`, the `callback` is invoked only after all resources complete prefetching; if the wait times out, the API returns `32104`.
- `awaitTimeout` (optional): Type `number`, in milliseconds, default `60000`. This only takes effect when `awaitComplete = true`.

### Return Value

None (`undefined`).

## Errors

- When there is a parameter error, the `code` returns `32101`, and the `msg` contains detailed error information.
- When the Image prefetch helper does not exist, the `code` returns `32102`.
- When the Resource service does not exist, the `code` returns `32103`.
- When `awaitComplete` is enabled and waiting times out, the `code` returns `32104`.

## Example

```js
import { useState, useEffect } from '@lynx-js/react';

function Page() {
  const [show, setShow] = useState(false);

  useEffect(() => {
    // We initiate resource preloading ahead of time when the page DidMount
    // We need to preload a batch of resources, including two images and two videos.
    // First, prepare the resource parameters, assign priority and cacheTarget for images, and the required preloadKey for videos.
    let resData = [
      {
        uri: 'https://xxxxx1.jpg',
        type: 'image',
        params: { priority: 'high', cacheTarget: 'disk' },
      },
      {
        uri: 'https://xxxxx2.jpg',
        type: 'image',
        params: { cacheTarget: 'bitmap' },
      },
      {
        uri: 'https://zzzzz1.mp4',
        type: 'video',
        params: { preloadKey: 'zzzzz1' },
      },
      {
        uri: 'https://zzzzz2.mp4',
        type: 'video',
        params: { preloadKey: 'zzzzz2' },
      },
      {
        uri: 'https://my-font-src',
        type: 'font',
      },
    ];

    // Call the requestResourcePrefetch to initiate preloading
    lynx.requestResourcePrefetch?.(
      {
        data: resData,
      },
      (res) => {
        if (res.code == 0) {
          console.log('success!');
        } else {
          console.log('fail! ', res.msg);
        }
        console.log(
          'prefetch status of each resource:',
          JSON.stringify(res.details),
        );
      },
      {
        awaitComplete: true,
        awaitTimeout: 3000,
      },
    );
  }, []);

  const handleTap = () => {
    // Change the show state through setState to control the display of images and videos
    setShow(!show);
  };

  return (
    <view onTap={handleTap}>
      {/* According to the show status to determine whether to display the image, note that here src is the unique key mentioned above, this should keep the src consistent with the preload time */}
      {show && <image src="https://xxxxx1.jpg" />}
      {show && <image src="https://xxxxx2.jpg" />}
      {/* According to the show status to determine whether to display the video, note that here preload-key is the unique key mentioned above, this should keep the preload-key consistent with the preload time */}
      {show && <x-video-pro src="https://zzzzz1.mp4" preload-key="zzzzz1" />}
      {show && <x-video-pro src="https://zzzzz2.mp4" preload-key="zzzzz2" />}
    </view>
  );
}

export default Page;
```

## Compatibility

**Compatibility Table**

**Query:** `lynx-api.lynx.requestResourcePrefetch`

[Source](https://github.com/lynx-family/lynx-website/tree/main/packages/lynx-compat-data/lynx-api/lynx/requestResourcePrefetch.json)

| Feature | Android | HarmonyOS | iOS | macOS | Windows | Web |
| --- | --- | --- | --- | --- | --- | --- |
| requestResourcePrefetch | Yes (2.6) | Yes (3.5) | Yes (2.8) | Yes (3.5) | Yes (3.5) | No |

**`requestResourcePrefetch`**

Used to request the prefetch of resource.

