预拉取能够在ASCF元服务框架启动的时候提前向第三方服务器拉取业务数据,当元服务代码包加载完时可以更快地渲染页面,减少用户等待时间,从而提升元服务的打开速度。
数据预拉取支持通过以下两种方式配置:
配置示例:
在preload.json中配置
[
{
"fetchType": "pre",
"url": "https://www.example.com",
"method": "POST",
"data": {
"x": ""
},
"headers": {
"content-type": "application/json"
},
"dataType": "json"
}
] 在ext.json中配置
{
"ext": {
"preload": [
{
"fetchType": "pre",
"url": "https://www.example.com",
"method": "POST",
"data": {
"x": ""
},
"headers": {
"content-type": "application/json"
},
"dataType": "json"
}
]
}
} 配置参数说明
| 节点 | 属性 | 类型 | 必填 | 描述 |
|---|---|---|---|---|
| / | fetchType | string | 是 | 数据预拉取类型,当前仅支持pre。 |
| / | params | Object | 是 | 预拉取网络请求http配置。 |
| params | url | string | 是 | 请求URL。 |
| params | method | string | 是 | HTTP请求方法。支持GET、POST。 |
| params | data | Object | 否 | 请求的参数。 |
| params | headers | Object | 否 | 自定义请求头。 |
| params | dataType | string | 否 | 期望返回的数据格式。仅支持json。 |
用户登录元服务后,可通过has.setBackgroundFetchToken设置一个自定义TOKEN字符串,更新后的TOKEN会在下一次预拉取向开发者服务器发起请求时带上,用于服务器校验请求合法性。
has.setBackgroundFetchToken是可选接口,非必须调用。
使用示例:
App({
onLaunch(options) {
has.setBackgroundFetchToken({
token: 'test_token',
success: () => {
console.info('setBackgroundFetchToken success');
}
});
}
}); 用户启动元服务时,可调用has.getBackgroundFetchData或has.onBackgroundFetchData获取已缓存到本地的数据。
使用示例:
App({
onLaunch(options) {
has.getBackgroundFetchData({
fetchType: 'pre',
success: (res) => {
console.info('getBackgroundFetchData success', res.fetchedData); // 缓存数据
}
});
has.onBackgroundFetchData((res) => {
console.info('onBackgroundFetchData listen success', res.fetchType); // 预拉取类型
console.info('onBackgroundFetchData listen success', res.fetchedData); // 缓存数据
});
}
});