rn-h5-preloader
TypeScript icon, indicating that this package has built-in type declarations

0.1.4 • Public • Published

rn-h5-preloader

React Native 插件,用于预加载 WebView 中的 H5 内容,解决首次加载慢的问题。

安装

npm install rn-h5-preloader
#
yarn add rn-h5-preloader

确保您已经安装了 peer dependencies:

npm install react-native-webview
#
yarn add react-native-webview

功能

  • 在应用启动时预加载 H5 内容,提高页面加载速度
  • 使用隐藏的 WebView 进行预加载,避免跨域问题
  • 支持预加载多个 URL
  • 与用户自己的 WebView 组件兼容,无需使用自定义组件

使用方法

1. 初始化并预加载 H5 内容

在应用启动时(如 App.js)初始化预加载:

// 方法1:使用顶层init方法(最简单)
import { init } from 'rn-h5-preloader';

init(
  [
    'https://example.com/page1',
    'https://example.com/page2'
  ],
  {
    timeout: 30000,
    cacheExpiration: 10 * 60 * 1000, // 10分钟
    useInteractionManager: true, // 使用InteractionManager优化加载时机,默认为true
  }
);

// 方法2:使用H5PreloadManager
// import { H5PreloadManager } from 'rn-h5-preloader';
//
// H5PreloadManager.init(
//   [
//     'https://example.com/page1',
//     'https://example.com/page2'
//   ],
//   {
//     timeout: 30000,
//     cacheExpiration: 10 * 60 * 1000, // 10分钟
//   }
// );

2. 在您的 WebView 组件中使用预加载内容

在您的 WebView 组件中,您可以检查 URL 是否已预加载:

import React from 'react';
import { View } from 'react-native';
import { WebView } from 'react-native-webview';
import { H5PreloadManager } from 'rn-h5-preloader';

const MyWebView = ({ url }) => {
  // 检查是否已预加载
  const preloadManager = H5PreloadManager.getInstance();
  const isPreloaded = preloadManager.isPreloaded(url);

  console.log('是否已预加载:', isPreloaded);

  return (
    <View style={{ flex: 1 }}>
      <WebView
        source={{ uri: url }}
        // 您可以使用自己的WebView配置
      />
    </View>
  );
};

export default MyWebView;

3. 检查预加载状态

您可以使用 H5PreloadManager 来检查预加载状态:

import { H5PreloadManager } from 'rn-h5-preloader';

// 检查是否已预加载
const preloadManager = H5PreloadManager.getInstance();
const isPreloaded = preloadManager.isPreloaded('https://example.com/page1');

console.log('是否已预加载:', isPreloaded);

// 清除缓存
preloadManager.clearCache();
// 或清除特定URL的缓存
preloadManager.clearCache('https://example.com/page1');

API 参考

顶层 API

函数 描述
init(urls, options?) 初始化并预加载多个URL(推荐使用)

H5PreloadManager

H5PreloadManager 是一个单例类,用于管理 H5 页面的预加载和缓存。

主要方法

方法 描述
init(urls, options?) 初始化并预加载多个URL(静态方法)
getInstance() 获取单例实例
preload(url, options?) 预加载 H5 页面
isPreloaded(url) 检查 URL 是否已预加载
clearCache(url?) 清除缓存,不提供url则清除所有缓存
setDefaultOptions(options) 设置默认预加载选项

预加载选项

选项 类型 默认值 描述
timeout number 30000 预加载超时时间(毫秒)
headers object undefined 请求头
userAgent string undefined 用户代理
cacheExpiration number 300000 缓存过期时间(毫秒)
useInteractionManager boolean true 是否使用InteractionManager优化加载时机,在动画和交互完成后再执行预加载

许可证

MIT

Package Sidebar

Install

npm i rn-h5-preloader

Weekly Downloads

13

Version

0.1.4

License

MIT

Unpacked Size

26.2 kB

Total Files

10

Last publish

Collaborators

  • moving_bricks