Data prefetch retrieves service data from third-party servers in advance during ASCF atomic service startup. It enables quicker rendering of pages once the atomic service code package has been loaded, thereby reducing users' waiting time and boosting the atomic service launch speed.
You can configure data prefetch in either of the following ways:
Create the preload.json file in the root directory of the atomic service and add preloading configurations.
Add preloading configurations under the ext property in the third-party platform configuration file ext.json.
Configuration examples:
Configurations in preload.json
[
{
"fetchType": "pre",
"url": "https://www.example.com",
"method": "POST",
"data": {
"x": ""
},
"headers": {
"content-type": "application/json"
},
"dataType": "json"
}
] Configurations in ext.json
{
"ext": {
"preload": [
{
"fetchType": "pre",
"url": "https://www.example.com",
"method": "POST",
"data": {
"x": ""
},
"headers": {
"content-type": "application/json"
},
"dataType": "json"
}
]
}
} Configuration parameters
| Node | Property | Type | Mandatory | Description |
|---|---|---|---|---|
| / | fetchType | string | Yes | Data prefetch type. Currently, only pre is supported. |
| / | params | Object | Yes | HTTP request parameters for data prefetch. |
| params | url | string | Yes | Request URL. |
| params | method | string | Yes | HTTP request method. GET and POST are supported. |
| params | data | Object | No | Request parameter. |
| params | headers | Object | No | Custom request header. |
| params | dataType | string | No | Expected return data format. Only json is supported. |
After a user signs in to the atomic service, you can use has.setBackgroundFetchToken to set a custom token. The updated token will be carried when the next data prefetch request is sent to your server for the server to verify the request validity.
has.setBackgroundFetchToken is optional.
Example:
App({
onLaunch(options) {
has.setBackgroundFetchToken({
token: 'test_token',
success: () => {
console.info('setBackgroundFetchToken success');
}
});
}
}); When a user opens the atomic service, the framework initiates an HTTP request based on relevant configurations. If the request is successful, the framework caches the request result for subsequent retrieval.
When a user launches the atomic service, you can call has.getBackgroundFetchData or has.onBackgroundFetchData to obtain the data cached locally.
Example:
App({
onLaunch(options) {
has.getBackgroundFetchData({
fetchType: 'pre',
success: (res) => {
console.info('getBackgroundFetchData success', res.fetchedData); // Cached data.
}
});
has.onBackgroundFetchData((res) => {
console.info('onBackgroundFetchData listen success', res.fetchType); // Prefetch type.
console.info('onBackgroundFetchData listen success', res.fetchedData); // Cached data.
});
}
});