H5 container resource interception
H5 pages with many images can load slowly due to repeated network requests. Use the H5 Container's resource interception mechanism to serve files from a local cache instead, reducing load times without modifying your H5 page code.
How it works
The H5 Container intercepts each resource request before it reaches the network. When a requested resource is already cached locally, the container returns it from disk. When it is not cached, the container falls back to loading from the network and triggers a background download for future requests. This interception is transparent to your H5 page—the resource URLs remain unchanged.
To implement resource interception, extend the H5ResProvider class and override two methods:
contains: called first for each request—returntrueto intercept and serve from cache, orfalseto let the request pass through to the networkgetResource: called only whencontainsreturnstrue—return the cachedInputStream, or fall back to opening the URL from the network if the cached stream is unavailable
Implement resource interception
Prerequisites
Before you begin, ensure that you have:
An Android project with the mPaaS SDK integrated
The
H5ResProviderclass available from the HTML5 Container and Offline Package module
Procedure
-
Inherit the
H5ResProviderclass and override thecontainsandgetResourcemethods.containsdecides whether to intercept the request:// Return true to intercept and use a local resource. Return false to not intercept and load from the network. @Override public boolean contains(String sourceUrl) { if (isCache(sourceUrl)) { if (ResourceCache.contains(sourceUrl)) { LoggerFactory.getTraceLogger().debug(TAG, "contains: " + sourceUrl); return true; } else { ResourceCache.download(sourceUrl); return false; } } return false; }getResourcereturns the resource whencontainshas returnedtrue:@Override public InputStream getResource(String sourceUrl) { // Get the resource 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 the resource from the network URL. try { return new URL(sourceUrl).openStream(); } catch (IOException e) { e.printStackTrace(); } } return null; } -
Register your
H5ResProviderimplementation before the H5 Container loads any pages.public static void register() { H5Utils.setProvider(H5ResProvider.class.getName(), new GapResProvider()); }
By customizing H5ResProvider, you control whether to intercept each loaded resource and how to retrieve it—reading from a local cache or a network URL. This lets you implement custom logic for your business scenarios.