All Products
Search
Document Center

Implement resource interception of H5 Container

Last Updated: Aug 16, 2021

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.

  1. Inherit the H5ResProvider class provided by the H5 Container, and override the contains method and getResource method.

    1. //return true means intercepting (using local resources), while fasle means not intercepting (loading resources online)
    2. @Override
    3. public boolean contains(String sourceUrl) {
    4. if (isCache(sourceUrl)) {
    5. if (ResourceCache.contains(sourceUrl)) {
    6. LoggerFactory.getTraceLogger().debug(TAG, "contains: " + sourceUrl);
    7. //Do not intercept.
    8. return true;
    9. } else {
    10. ResourceCache.download(sourceUrl);
    11. return false;
    12. }
    13. }
    14. return false;
    15. }
    1. @Override
    2. public InputStream getResource(String sourceUrl) {
    3. //Get resources from the local cache.
    4. if (isCache(sourceUrl)) {
    5. if (ResourceCache.contains(sourceUrl)) {
    6. try {
    7. InputStream inputStream = ResourceCache.getResource(sourceUrl);
    8. if (null == inputStream) {
    9. LoggerFactory.getTraceLogger().debug(TAG, "File null: " + sourceUrl);
    10. return new URL(sourceUrl).openStream();
    11. }
    12. LoggerFactory.getTraceLogger().debug(TAG, "getResource: " + sourceUrl);
    13. return inputStream;
    14. } catch (Exception e) {
    15. }
    16. }
    17. } else {
    18. //Get resources from network links.
    19. try {
    20. return new URL(sourceUrl).openStream();
    21. } catch (IOException e) {
    22. e.printStackTrace();
    23. }
    24. }
    25. return null;
    26. }
  2. Register H5ResProvider.

    1. public static void register() {
    2. H5Utils.setProvider(H5ResProvider.class.getName(), new GapResProvider());
    3. }

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.