There are too many images displayed on the page of an App, which causing the slow loading speed. Thus, it is necessary to optimize the loading speed of the H5 Container, and strive to achieve the H5 page opening in seconds. The H5 Container can greatly improve the loading speed of H5 page by intercepting and replacing the resource files(replace the files that need to be loaded online with local cache files). The demo is as follows, for reference only.
Inherit the
H5ResProvider
class provided by the H5 Container, and override thecontains
method andgetResource
method.//return true means intercepting (using local resources), while fasle means not intercepting (loading resources online)
@Override
public boolean contains(String sourceUrl) {
if (isCache(sourceUrl)) {
if (ResourceCache.contains(sourceUrl)) {
LoggerFactory.getTraceLogger().debug(TAG, "contains: " + sourceUrl);
//Do not intercept.
return true;
} else {
ResourceCache.download(sourceUrl);
return false;
}
}
return false;
}
@Override
public InputStream getResource(String sourceUrl) {
//Get resources from the local cache.
if (isCache(sourceUrl)) {
if (ResourceCache.contains(sourceUrl)) {
try {
InputStream inputStream = ResourceCache.getResource(sourceUrl);
if (null == inputStream) {
LoggerFactory.getTraceLogger().debug(TAG, "File null: " + sourceUrl);
return new URL(sourceUrl).openStream();
}
LoggerFactory.getTraceLogger().debug(TAG, "getResource: " + sourceUrl);
return inputStream;
} catch (Exception e) {
}
}
} else {
//Get resources from network links.
try {
return new URL(sourceUrl).openStream();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
Register
H5ResProvider
.public static void register() {
H5Utils.setProvider(H5ResProvider.class.getName(), new GapResProvider());
}
By using customizing H5ResProvider
, users can decide whether to intercept loaded resources and select the resource acquisition methods (using local resources, loading resources online), and users can customize their own business scenarios.